Dart/Flutter 使用日期时 For 循环出错(国际)

Dart/Flutter Error in For Loop when work with Date (intl)

在我的应用程序中,我制作了一个 for 循环,打印连续 600 个连续日期以匹配用户输入的日期。我将 INTL 库用于日期。这是代码的一部分:

var date = []; // is the list that will contain all dates.
unformatted_date = Datetime.now(); //or the one entered by the user

for(var i = 1; i<600; i++){
   date.add(unformatted_date.add(Duration(days: i)));
}

例如,如果我将初始日期插入 2021 年 5 月 5 日,则循环总是打印两次 10 月 30 日。即使在其他日期,它也恰好有两个相等。很少发生日期不存在,没有打印的情况

问题很可能是DST(夏令时)。重要的是要了解 DateTime 上的 add() 记录在案:

Notice that the duration being added is actually 50 * 24 * 60 * 60 seconds. If the resulting DateTime has a different daylight saving offset than this, then the result won't have the same time-of-day as this, and may not even hit the calendar date 50 days later.

Be careful when working with dates in local time.

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

因此,如果您添加一天,它会假定这一天是 24 小时,这在夏令时变化的情况下是不正确的。

DateTime 上进行加法时,您应该改用 UTC 时间(因为 UTC 没有夏令时),如果时间对于正确显示很重要,则在需要显示日期时将其转换回本地时间给用户。