Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing only dates of DateTimes in Dart

I need to store and compare dates (without times) in my app, without caring about time zones.
I can see three solutions to this:

  1. (date1.year == date2.year && date1.month == date2.month && date1.day == date2.day)
    This is what I'm doing now, but it's horrible verbose.

  2. date1.format("YYYYMMDD") == date2.format("YYYYMMDD")
    This is still rather verbose (though not as bad), but just seems inefficient to me...

  3. Create a new Date class myself, perhaps storing the date as a "YYYYMMDD" string, or number of days since Jan 1 1980. But this means re-implementing a whole bunch of complex logic like different month lengths, adding/subtracting and leap years.

Creating a new class also avoids an edge case I'm worried about, where adding Duration(days: 1) ends up with the same date due to daylight saving changes. But there are probably edge cases with this method I'm not thinking of...

Which is the best of these solutions, or is there an even better solution I haven't thought of?

like image 260
Lucas Avatar asked Oct 24 '18 21:10

Lucas


People also ask

Can you compare DateTimes?

Compare() method in C# is used for comparison of two DateTime instances. It returns an integer value, <0 − If date1 is earlier than date2. 0 − If date1 is the same as date2.

How do you compare two dates in Dart Flutter?

Simply use the methods isAfter() , isBefore() or isAtSameMomentAs() from DateTime . Other alternative, use compareTo(DateTime other) , as in the docs: Compares this DateTime object to [other], returning zero if the values are equal. Returns a negative value if this DateTime [isBefore] [other].

How do you know if a date is greater than today in Flutter?

if (date(DateTime. now()). difference(date(lastDailyCheck)). inHours > 0) { // "One day" after. }

How do you parse a date in darts?

DateFormat is used to convert / parse dates into specific format (ex : yyyy-MM-d, yy-MM-dd). In order to use this class, we need to add intl as a dependency in pubspec. yaml and then import the package in the dart file.


7 Answers

Since I asked this, extension methods have been released in Dart. I would now implement option 1 as an extension method:

extension DateOnlyCompare on DateTime {
  bool isSameDate(DateTime other) {
    return year == other.year && month == other.month
           && day == other.day;
  }
}
like image 88
Lucas Avatar answered Oct 03 '22 21:10

Lucas


You can use compareTo:

  var temp = DateTime.now().toUtc();
  var d1 = DateTime.utc(temp.year,temp.month,temp.day);
  var d2 = DateTime.utc(2018,10,25);     //you can add today's date here
  if(d2.compareTo(d1)==0){
    print('true');
  }else{
    print('false');
  }
like image 24
yashthakkar1173 Avatar answered Oct 03 '22 20:10

yashthakkar1173


DateTime dateTime = DateTime.now();
DateTime _pickedDate = // Some other DateTime instance

dateTime.difference(_pickedDate).inDays == 0 // <- this results to true or false

Because difference() method of DateTime return results as Duration() object, we can simply compare days only by converting Duration into days using inDays property

like image 22
Henry Lyamuya Avatar answered Oct 03 '22 21:10

Henry Lyamuya


Use instead the package: dart_date Dart Extensions for DartTime

dart_date provides the most comprehensive, yet simple and consistent toolset for manipulating Dart dates.

dart_date

DateTime now = DateTime.now();
DateTime date = ....;
if (date.isSameDay(now)) {
  //....
} else {
  //....
}

Also here the difference in days :

int differenceInDays(DateTime a, DateTime b) => a.differenceInDays(b);
like image 29
Mike Avatar answered Oct 03 '22 22:10

Mike


I am using this function to calculate the difference in days.

Comparing dates is tricky as the result depends not just on the timestamps but also the timezone of the user.

int diffInDays (DateTime date1, DateTime date2) {
    return ((date1.difference(date2) - Duration(hours: date1.hour) + Duration(hours: date2.hour)).inHours / 24).round();
}
like image 30
Edwin Liu Avatar answered Oct 03 '22 21:10

Edwin Liu


Use isAtSameMomentAs:

var date1 = DateTime.now();
var date2 = date1.add(Duration(seconds: 1));

var isSame = date1.isAtSameMomentAs(date2); // false 
like image 22
CopsOnRoad Avatar answered Oct 03 '22 21:10

CopsOnRoad


The easiest option is just to use DateUtils

For example

if (DateUtils.isSameDay(date1, date2){
   print('same day')
}

isSameDay takes in 2 DateTime objects and ignores the time element

like image 41
Andrew Avatar answered Oct 03 '22 20:10

Andrew