Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
945 views
in Technique[技术] by (71.8m points)

time - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...