Comparing only dates of DateTimes in Dart

纵然是瞬间 提交于 2020-05-10 07:33:00

问题


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?


回答1:


You can use difference:

int diffDays = date1.difference(date2).inDays;
bool isSame = (diffDays == 0);



回答2:


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');
  }



回答3:


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 this.year == other.year && this.month == other.month
           && this.day == other.day;
  }
}



回答4:


I ended up using this Dart package, which is basically option 3.




回答5:


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();
}



回答6:


If you want calculate difference in a simple way, without consider Timezone, or hour of the day, but only the day like a calendar, this is a one solution

  DateTime date = DateTime.fromMicrosecondsSinceEpoch(1562022000);
  print(DateTime.now().day - date.day);

The result is 2;



来源:https://stackoverflow.com/questions/52978195/comparing-only-dates-of-datetimes-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!