Luc*_*cas 6 time date dart flutter
我需要在我的应用中存储和比较日期(无时间),而无需关心时区。
我可以看到三种解决方案:
(date1.year == date2.year && date1.month == date2.month && date1.day == date2.day)
这就是我现在正在做的事情,但是太冗长了。
date1.format("YYYYMMDD") == date2.format("YYYYMMDD")
这仍然很冗长(尽管还不算太糟),但对我来说似乎效率不高...
自己创建一个新的Date类,也许将日期存储为“ YYYYMMDD”字符串或自1980年1月1日以来的天数。但这意味着重新实现一堆复杂的逻辑,例如不同的月长,加/减和/年。
创建新类也避免了我担心的极端情况,Duration(days: 1)由于夏令时的更改,添加结果的日期相同。但是我可能没有想到这种方法的一些极端情况...
这些解决方案中哪一个最好,还是我没有想到的更好的解决方案?
Luc*_*cas 51
自从我问这个以来,Dart 中已经发布了扩展方法。我现在将选项 1 实现为扩展方法:
extension DateOnlyCompare on DateTime {
bool isSameDate(DateTime other) {
return this.year == other.year && this.month == other.month
&& this.day == other.day;
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*rew 31
The easiest option is just to use DateUtils
For example
if (DateUtils.isSameDay(date1, date2)){
print('same day')
}
Run Code Online (Sandbox Code Playgroud)
isSameDay takes in 2 DateTime objects and ignores the time element, and that function exists in flutter/material.dart
小智 11
您可以使用差异:
int diffDays = date1.difference(date2).inDays;
bool isSame = (diffDays == 0);
Run Code Online (Sandbox Code Playgroud)
yas*_*173 10
您可以使用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');
}
Run Code Online (Sandbox Code Playgroud)
小智 9
DateTime dateTime= DateTime.now();
DateTime _pickedDate = // Some other DateTime instance
dateTime.difference(_pickedDate).inDays == 0 // <- this results to true or false
Run Code Online (Sandbox Code Playgroud)
因为 DateTime 的 difference() 方法将结果返回为 Duration() 对象,所以我们可以通过使用 inDays 属性将 Duration 转换为天数来简单地比较天数
小智 5
使用包:dart_date Dart Extensions for DartTime
dart_date 提供了最全面、最简单且一致的工具集来操作 Dart 日期。
DateTime now = DateTime.now();
DateTime date = ....;
if (date.isSameDay(now)) {
//....
} else {
//....
}
Run Code Online (Sandbox Code Playgroud)
这里还有天数的差异:
int differenceInDays(DateTime a, DateTime b) => a.differenceInDays(b);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5068 次 |
| 最近记录: |