首页 > 解决方案 > 向日期添加天数无法正常工作

问题描述

我正在尝试将日期添加到日期,但我不明白结果,这是我的代码:

void testDate(){
  DateTime start = DateTime(2019,10,1);
  DateTime end = DateTime(2019,11,1);

  List<DateTime> list = new List();
  DateTime current = DateTime.fromMillisecondsSinceEpoch(start.millisecondsSinceEpoch);

  while(current.isBefore(end)){
    list.add(DateTime.fromMillisecondsSinceEpoch(current.millisecondsSinceEpoch));
    Duration duration = Duration(days:3);
    current = current.add(duration);
    print(current);
    current = DateTime(current.year,current.month,current.day);
  }
}

我得到了这个结果:

2019-10-04 00:00:00.000
2019-10-07 00:00:00.000
2019-10-10 00:00:00.000
2019-10-13 00:00:00.000
2019-10-16 00:00:00.000
2019-10-19 00:00:00.000
2019-10-22 00:00:00.000
2019-10-25 00:00:00.000
2019-10-27 23:00:00.000
2019-10-29 23:00:00.000
2019-11-01 00:00:00.000

为什么 2019-10-25 00:00:00.000 + 3 天 = 2019-10-27 23:00:00.000 ?应该是 2019-10-28 00:00:00.000

标签: flutterdart

解决方案


该文档指出:

“请注意,添加的持续时间实际上是 50 * 24 * 60 * 60 秒。如果生成的 DateTime 具有与此不同的夏令时偏移量,则结果将不会具有与此相同的时间,并且可能甚至没有达到 50 天后的日历日期。

使用当地时间的日期时要小心。”

可能有一个夏令时开始之间

2019-10-25 00:00:00.000

2019-10-27 23:00:00.000

在以下位置查看:

https://api.flutter.dev/flutter/dart-core/DateTime/add.html


推荐阅读