dart DateTime 差异错误(28.3 到 27.3 之间)
dart DateTime difference bug (between 28.3 to 27.3)
试试这个(在 https://dartpad.dev/ 中):
int day = 28;
DateTime day1 = DateTime(2020, 3, day);
DateTime day2 = DateTime(2020, 3, day - 1);
print(day1.difference(day2).inDays);
结果应该是 1,结果是 0...
用任何其他值替换 "day" 变量,它给出正确的结果 (1)...
这是一个错误吗?
嗯,问题归结为 difference
的 return 值,即:
The difference is measured in seconds and fractions of seconds. The difference above counts the number of fractional seconds between midnight at the beginning of those dates. If the dates above had been in local time, not UTC, then the difference between two midnights may not be a multiple of 24 hours due to daylight saving differences.
https://api.dart.dev/stable/2.7.2/dart-core/DateTime/difference.html
所以我们从difference
得到的值是一个Duration
对象,包含两个DateTime
对象之间的秒差。然后,您可以要求 Duration
以天为单位表示此结果。
问题在于,由于三月的夏令时,许多国家/地区正在调整时钟。事实上,自从我在丹麦以来,您的示例在我的计算机上没有显示任何错误。所以我将您的代码更改为:
void main() {
for (var day = 1; day <= 31; day++) {
DateTime day1 = DateTime(2020, 3, day);
DateTime day2 = DateTime(2020, 3, day - 1);
print('Day $day: inDays: ${day1.difference(day2).inDays} inHours: ${day1.difference(day2).inHours}');
}
}
return我的计算机上有以下内容:
Day 27: inDays: 1 inHours: 24
Day 28: inDays: 1 inHours: 24
Day 29: inDays: 1 inHours: 24
Day 30: inDays: 0 inHours: 23
Day 31: inDays: 1 inHours: 24
因为我们实际上在更改为夏令时时删除了一天中的一个小时,所以 returned 持续时间不包含 24 小时而是 23.
试试这个(在 https://dartpad.dev/ 中):
int day = 28;
DateTime day1 = DateTime(2020, 3, day);
DateTime day2 = DateTime(2020, 3, day - 1);
print(day1.difference(day2).inDays);
结果应该是 1,结果是 0... 用任何其他值替换 "day" 变量,它给出正确的结果 (1)...
这是一个错误吗?
嗯,问题归结为 difference
的 return 值,即:
The difference is measured in seconds and fractions of seconds. The difference above counts the number of fractional seconds between midnight at the beginning of those dates. If the dates above had been in local time, not UTC, then the difference between two midnights may not be a multiple of 24 hours due to daylight saving differences.
https://api.dart.dev/stable/2.7.2/dart-core/DateTime/difference.html
所以我们从difference
得到的值是一个Duration
对象,包含两个DateTime
对象之间的秒差。然后,您可以要求 Duration
以天为单位表示此结果。
问题在于,由于三月的夏令时,许多国家/地区正在调整时钟。事实上,自从我在丹麦以来,您的示例在我的计算机上没有显示任何错误。所以我将您的代码更改为:
void main() {
for (var day = 1; day <= 31; day++) {
DateTime day1 = DateTime(2020, 3, day);
DateTime day2 = DateTime(2020, 3, day - 1);
print('Day $day: inDays: ${day1.difference(day2).inDays} inHours: ${day1.difference(day2).inHours}');
}
}
return我的计算机上有以下内容:
Day 27: inDays: 1 inHours: 24
Day 28: inDays: 1 inHours: 24
Day 29: inDays: 1 inHours: 24
Day 30: inDays: 0 inHours: 23
Day 31: inDays: 1 inHours: 24
因为我们实际上在更改为夏令时时删除了一天中的一个小时,所以 returned 持续时间不包含 24 小时而是 23.