How to compare current date with date from the picker - datetime

I have a datetimepicker which i used to get the date and set it as label in my screen. Now i want to check if the entered date is valid or not. i.e., the entered date should be bigger than or equal to the current date. Please tell with a code. Thank you
StringBuffer dateStrDate = new StringBuffer();
Calendar Cal = datePickerDate.getDateTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("yy:mm:dd");
dateFormat.format(Cal, dateStrDate, null);
time.setText(dateStrDate.toString());

DateTimePicker datePicker = DateTimePicker.createInstance(Calendar.getInstance(), "yyyy-MM-dd", null);
if(datePicker.doModal()) {
Calendar cal = datePicker.getDateTime();
int month=cal.get(cal.MONTH);
int year=cal.get(cal.YEAR);
int date1=cal.get(cal.DATE);
}

Related

Convert publishedAt (API TIME) into normal time

1.Do I have to have two views in xml layout, one for time and one for date? but in the URL (when I read the information in JSON formatter publishedAt (has time and date)
So how do I convert the time stamp of JSON into normal time.
The time or date you can say is in this format 2020-01-09T14:50:58.000Z
Should I convert it when I am in my Adapter file or should I do it in the QueryUtils where I am creating and extracting things from JSON.
**My QueryUtils.java**
try {
JSONObject baseJsonResponse = new JSONObject(bookJson);
JSONArray newsArray = baseJsonResponse.getJSONArray("articles");
for (int i = 0; i < newsArray.length(); i++) {
JSONObject currentNews = newsArray.getJSONObject(i);
/*JSONObject properties = currentNews.getJSONObject("articles");*/
JSONObject newsSource = currentNews.getJSONObject("source");
String title = currentNews.getString("title");
String description = currentNews.getString("description");
String url = currentNews.getString("url");
/*String name = properties.getString("name");*/
String name = newsSource.getString("name");
String time = currentNews.getString("publishedAt");
String image = currentNews.getString("urlToImage");
News news = new News (title, description, url, name, time, image);
newss.add(news);
My Adapterjava file is
TextView dateView = (TextView) listItemView.findViewById(R.id.date);
dateView.setText(currentNews.getTime());
I want to display my time and date together can someone help please?
Data model versus presentation
Parse your input string 2020-01-09T14:50:58.000Z immediately as a Instant object. The Z on the end means UTC (an offset of zero hours-minutes-seconds).
Instant instant = Instant.parse( "2020-01-09T14:50:58.000Z" ) ;
Store that Instant object in your data model.
When it comes to presentation in your user-interface, adjust the Instant (always in UTC) to the time zone expected/desired by the user.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Then let java.time automatically localize. Specify a Locale to determine the human language and cultural norms used in localizing. The Locale has nothing to do with the time zone.
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( locale ) ;
String output = zdt.format( f ) ;
This has all been covered many times on Stack Overflow. So search to learn more.

DateTime in UTC not converting to Local

I'm receiving a DateTime response from API that's sets the timezone to UTC.
But when I try to convert the received data using toLocal() it doesn't convert.
my local time is HKT
here's my code.
//TIME DIFFERENCE
getNotificationDate(DateTime date) {
date = date.toUtc();
final convertedDate = date.toLocal();
final dateNow = DateTime.now();
print('TIMENOW: ' + dateNow.toString());
print('TIMENOTIFC: ' + convertedDate.toString());
final difference = dateNow.difference(convertedDate);
print('DIFFERENCE: ' + difference.toString());
return getDurationFormat(difference);
}
EDIT:
date is the DateTime I'm receiving from the API. which is in UTC timezone.
I used print('TIMEZONENAME: ' + date.timeZoneName; and it automatically sets the timezone to HKT. that's why it does nothing when I try to use date.toLocal()
Flutter gave us the easiest way to convert it.
You just need to pass utc: true while parsing your date.
var dateTime = DateFormat("yyyy-MM-dd HH:mm:ss").parse(dateUtc, true);
var dateLocal = dateTime.toLocal();
Input:
Assume my TimeZone : +05:30
UTC Date -> 2020-02-12 23:57:02.000
Output:
Local Date -> 2020-02-12 18:27:02.019660
// you have time in utc
var dateUtc = DateTime.now().toUtc();
print("dateUtc: $dateUtc"); // 2019-10-10 12:05:01
// convert it to local
var dateLocal = dateUtc.toLocal();
print("local: $dateLocal"); // 2019-10-10 14:05:01
Can you see the difference in hours, in utc it is 12 and locally it is 14.
Firstly, convert your Sting to DateTime.
> DateTime dateTime = DateTime.parse(json['pickUpTime']);
Secondly, add timeZoneOffSet to your converted date time it will convert utc to your local time.
> dateTime = dateTime.add(DateTime.parse(json['pickUpTime']).timeZoneOffset);
Final Code
DateTime dateTime = DateTime.parse(json['pickUpTime']);
dateTime = dateTime.add(DateTime.parse(json['pickUpTime']).timeZoneOffset);
You can try this code:
getNotificationDate(DateTime date) {
date = DateTime.utc(date.year,date.month,date.day,date.hour,date.minute,date.second);;
final convertedDate = date.toLocal();
final dateNow = DateTime.now();
print('TIMENOW: ' + dateNow.toString());
print('TIMENOTIFC: ' + convertedDate.toString());
final difference = dateNow.difference(convertedDate);
print('DIFFERENCE: ' + difference.toString());
return getDurationFormat(difference);
}
I've done something like this.
String dateTimeFormatter(String dateTime, {String? format}) {
return DateFormat(format ?? 'yyyy/MM/dd, hh:mm a')
.format(DateTime.parse(dateTime).toLocal())
.toString();
}
just pass the format which you want to display in your app.
If somebody needs to parse a UTC timestamp in isoformat, for example something like this:
>>> from datetime import datetime
>>> datetime.utcnow().format()
'2021-07-20T19:35:19.769891'
Then you can parse this and convert this to local time by
DateTime parseDatetimeFromUtc({required String isoFormattedString}){
var dateTime = DateTime.parse(isoFormattedString + '+00:00');
return dateTime.toLocal();
}
The '+00:00' is append here as the timezone information part which I do not send over my API to save some bytes. Maybe this helps someone who is in the same situation.
Of course you do not need this hardcoded suffix if you use a timezone aware timestamp in your backend:
>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2021-07-20T19:42:36.538195+00:00'
For those who parsing TimeStamp from Firestore.
*sentAt is Timestamp
String timeToDate = widget.sentAt.toDate().toString();
var dateTime = DateFormat("yyyy-MM-dd HH:mm:ss").parse(timeToDate, true);
var dateLocal = dateTime.toLocal();
this is how i converted to my required time .which was showing as
I/flutter ( 5709): 16 Apr 08:30 PM 2021
when using the
var date=DateFormat("dd MMM hh:mm a y").format(DateTime.fromMillisecondsSinceEpoch(start*1000));
print(date);
but after using this code i got my right time
var date=DateFormat("dd MMM hh:mm a y").format(DateTime.fromMillisecondsSinceEpoch(start*1000).toUtc());
print(date);
which is
I/flutter ( 5709): 16 Apr 03:00 PM 2021
I tried several examples and forums, but it kept getting me the incorrect date time for my zone, The only way I made it work correctly was by using the GMT package
var nowLocal = DateTime.now();
print("toUtc: ${nowLocal.toUtc()}");
print("toLocalDateTime ${nowLocal.toLocalDateTime()}");
print("toLocal ${nowLocal.toLocal()}");
print("toIso8601String ${nowLocal.toIso8601String()}");
final timeZoneOffsetInHours = DateTime.now().timeZoneOffset.inHours;
final nowGMT = await GMT.now();
print("GMT: $nowGMT");
final nowActual = nowGMT?.add(Duration(hours: timeZoneOffsetInHours));
print("nowActual $nowActual");
Two solutions I implemented
var date = DateFormat("yyyy-MM-ddTHH:mm:ss").parse(json, true);
var dateLocal = date.toLocal();
Other solutions add "Z"
You need to indicate a timezone to DateTime.parse, otherwise it assumes local time. From the dartdoc:
var date = DateTime.parse("${dateString}Z").toLocal();
var dateFormat = date2.toLocal();
Install intl package from pub.dev
add following line :
import 'package:intl/intl.dart';
You can make an extension like below so it will be very helpful and easy to use anywhere in a whole project.
//just make sure you have passed the right date format of utc("yyyy-MM-dd HH:mm:ss"). I have passed by default my format.
//for example
// 2020-11-25 24:12:36 -> "yyyy-MM-dd HH:mm:ss"
DateTime localDate=utcDateTime.toLocalDateTime();
//for different formats you can pass your own dateFormat for utcDate like below:
// 20-11-25 24:12:36 -> "yy-MM-dd HH:mm:ss"
DateTime localDate=utcDateTime.toLocalDateTime("yy-MM-dd HH:mm:ss");
extension DateTimeExtension on DateTime {
DateTime toLocalDateTime({String format = "yyyy-MM-dd HH:mm:ss"}) {
var dateTime = DateFormat(format).parse(this.toString(), true);
return dateTime.toLocal();
}
}
convert utc number to DateTime:
DateTime utcToDateTime(int utc) {
return DateTime(1970, 1, 1).add(Duration(seconds: utc));
}
//test
DateTime d = utcToDateTime(1649297709);
print(d);

rad date picker should load start date of current month automatically, when Page loads in asp.net

current month
current year
and start date(1 to be constant) in telerik rad date picker
Am working to get date 1= year,6 months back, 1
date2=year, current month, 1
i can get current date as below
startdatepicker.SelectedDate = DateTime.Now;
//startdatepicker.SelectedDate = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(-6), 1);//-->this not working
This should work, unless I misunderstand your question...
startdatepicker.SelectedDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
I got it by:
DateTime end = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
enddate.SelectedDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
start.SelectedDate = (end.AddMonths(-6));

How to compare two dates with each other in Flex?

I have a standard ISO8601 date string:
2004-02-12T15:19:21+00:00
I want to know if this date is older than 10 minutes ago in Flex. So basically:
if ("2004-02-12T15:19:21+00:00" > current_time - 10mins) {
// do whatever
}
What would the syntax be in Flex? I'm basically stuck at trying to convert the string into a Flex Date Object without parsing it character by character.
If you don;t care about the timezone i.e. the date string is in the same timezone as where you are running the application then this should work.
var date:Date = DateFormatter.parseDateString("2004-02-12T15:19:21+00:00");
var now:Date = new Date();
var tenMinAgo:Number = now.time - 1000*60*10;
if (date.time < tenMinAgo) {
trace("More than 10 min ago");
}

How to determine the entire date range displayed by ASP.NET calendar?

The ASP.NET calendar always displays 6 weeks of dates in a 7x6 grid. My problem is that the first day of the target month does not necessarily appear in the first row... in some cases, the entire first row displays dates from the previous month. In other cases, the entire last row displays dates from the next row.
Is there a reliable way to query the calendar object to determine the 42-day range that would be rendered for a specific month/year?
For example, consider June 2008 and Feb 2009:
Notice that the first week contains ONLY dates from prior month http://img371.imageshack.us/img371/2290/datesmq5.png
I assume that the calendar tries to avoid bunching all of the "other month" dates at either the top or bottom of the grid, and therefore puts the first of the target month on the 2nd row. I am looking for an easy way to determine that the displayed range for June 2008 is May 25 - July 5, for instance.
Looking at the public members exposed by the ASP.NET Calendar control I do not believe that this information is something that you can just get from the calendar control.
You have a few options as "workarounds" to this though, although not nice....but they would work.
You could manually calculate the first week values
You can handle the "day render" event to handle the binding of the individual days, and record min/max values.
Granted neither is elegant, but AFAIK it is the only real option
Edit
After discussion in the comments, another option is a modified version of my second option above. Basically the first time Day Render is called, get the block of data for the next 42 days, then you can simply search the list for the proper day value to display on future calls to DayRender, avoiding a DB hit for each day. Doing this is another "non-elegant" solution, but it works, and reduces a bit of load on the DB, but introduces some overhead on the application side.
It will be important here to define well structured page level properties to hold the items during the binding events, but to ensure that if a month changed, etc that it wasn't loaded incorrectly etc.
I wrote a couple of methods to help with this. Just pass in Calendar.VisibleDate:
public static DateTime GetFirstDateOfMonth(DateTime date)
{
return new DateTime(date.Year, date.Month, 1);
}
public static DateTime GetFirstDisplayedDate(DateTime date)
{
date = GetFirstDateOfMonth(date);
return date.DayOfWeek == DayOfWeek.Sunday ? date.AddDays(-7) : date.AddDays((int)date.DayOfWeek * -1);
}
public static List<DateTime> GetDisplayedDates(DateTime date)
{
date = GetFirstDisplayedDate(date);
List<DateTime> dates = new List<DateTime>();
for (int i = 0; i < 42; i++)
{
dates.Add(date.AddDays(i));
}
return dates;
}
I've just been looking into this myself, and got directed to here. I'm personally tempted to go with option two, because the alternative is messy. Ronnie's version is nice, but unfortunately doesn't take into account cultures with different FirstDayOfWeeks.
Using Reflector, we can see how it's done internally:
...
DateTime visibleDate = this.EffectiveVisibleDate();
DateTime firstDay = this.FirstCalendarDay(visibleDate);
...
private System.Globalization.Calendar threadCalendar =
DateTimeFormatInfo.CurrentInfo.Calendar;
private DateTime EffectiveVisibleDate()
{
DateTime visibleDate = this.VisibleDate;
if (visibleDate.Equals(DateTime.MinValue))
{
visibleDate = this.TodaysDate;
}
if (this.IsMinSupportedYearMonth(visibleDate))
{
return this.minSupportedDate;
}
return this.threadCalendar.AddDays(visibleDate,
-(this.threadCalendar.GetDayOfMonth(visibleDate) - 1));
}
private DateTime FirstCalendarDay(DateTime visibleDate)
{
DateTime date = visibleDate;
if (this.IsMinSupportedYearMonth(date))
{
return date;
}
int num = ((int)
this.threadCalendar.GetDayOfWeek(date)) - this.NumericFirstDayOfWeek();
if (num <= 0)
{
num += 7;
}
return this.threadCalendar.AddDays(date, -num);
}
private int NumericFirstDayOfWeek()
{
if (this.FirstDayOfWeek != FirstDayOfWeek.Default)
{
return (int) this.FirstDayOfWeek;
}
return (int) DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek;
}
private bool IsMinSupportedYearMonth(DateTime date)
{
return this.IsTheSameYearMonth(this.minSupportedDate, date);
}
private bool IsTheSameYearMonth(DateTime date1, DateTime date2)
{
return (((this.threadCalendar.GetEra(date1) ==
this.threadCalendar.GetEra(date2)) &&
(this.threadCalendar.GetYear(date1) ==
this.threadCalendar.GetYear(date2))) &&
(this.threadCalendar.GetMonth(date1) ==
this.threadCalendar.GetMonth(date2)));
}
Sadly, the functionality is already there, we just can't get at it!
Mitchel,
Worked perfectly, thank you.
Started with a public variable
bool m_FirstDay = false
in the day_render function
if(m_FirstDay == false)
{
DateTime firstDate;
DateTime lastDate;
firstDate = e.Day.Date;
lastDate = firstDate.AddDays(41);
m_FirstDay = true;
}
I then had the visible date range of the asp.net calendar control. Thanks again.
see this one.
How to Remove the Last Week Of a Calendar

Resources