【问题标题】:Dart/Flutter Error in For Loop when work with Date (intl)使用 Date (intl) 时 For 循环中的 Dart/Flutter 错误
【发布时间】:2022-01-24 13:29:24
【问题描述】:

在我的应用程序中,我创建了一个 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 日打印两次。即使在其他日期,它恰好有两个相等。很少发生日期不存在或未打印的情况

【问题讨论】:

    标签: flutter dart for-loop intl


    【解决方案1】:

    问题很可能是 DST(夏令时)。请务必了解,DateTime 上的 add() 记录在:

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

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

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

    因此,如果您添加一天,则假定该天是 24 小时,这在 DST 轮班的情况下不正确。

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

    【讨论】:

      猜你喜欢
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 2021-06-19
      相关资源
      最近更新 更多