仅比较Dart中的DateTimes日期 [英] Comparing only dates of DateTimes in Dart

查看:496
本文介绍了仅比较Dart中的DateTimes日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在应用中存储和比较日期(无时间),而不必关心时区。

我可以看到三种解决方案:

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)

    这是我现在正在做的,但是太冗长了。

  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.

date1.format( YYYYMMDD)== date2.format( YYYYMMDD)

这仍然很冗长(尽管还不错),但对我来说似乎效率不高...

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

我自己创建一个新的Date类,也许将日期存储为 YYYYMMDD字符串或自此以来的天数1980年1月1日。但这意味着重新实现一堆复杂的逻辑,例如不同的月长,加/减和leap年。

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.

创建一个新类也避免了我担心的一个极端情况,在其中添加 Duration(days:1)会由于白天而以相同的日期结束保存更改。但是使用这种方法可能存在一些边缘情况,而我却没有想到...

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?

推荐答案

因为我问了这个问题,所以扩展方法已在Dart中发布。我现在将选项1作为扩展方法实现:

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

这篇关于仅比较Dart中的DateTimes日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆