Comparing only dates of DateTimes in Dart

后端 未结 4 1445
予麋鹿
予麋鹿 2020-12-29 23:56

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 == da

相关标签:
4条回答
  • 2020-12-30 00:10

    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);
    
    0 讨论(0)
  • 2020-12-30 00:11

    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');
      }
    
    0 讨论(0)
  • 2020-12-30 00:16

    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();
    }
    
    0 讨论(0)
  • 2020-12-30 00:33

    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;
      }
    }
    
    0 讨论(0)
提交回复
热议问题