【问题标题】:Dart/Flutter Not converting local date time to UTC correctlyDart/Flutter 未正确将本地日期时间转换为 UTC
【发布时间】:2020-10-11 14:56:13
【问题描述】:

我正在构建一个颤振/firebase 聊天应用程序,并以 UTC 格式存储消息的时间戳。我正在使用这行代码将本地时间转换为 UTC。 'time': DateTime.now().toUtc().toString(), 当我对两个用户进行测试时,一个在美国弗吉尼亚州,另一个在斯里兰卡。斯里兰卡用户的时间戳正确转换为 UTC,但弗吉尼亚用户的时间正确但日期为昨天。

斯里兰卡时间:2020-06-21 20:50:48

UTC 转换:2020-06-21 15:20:48.027446Z

弗吉尼亚时间:2020-06-21 11:24:38

UTC 转换:2020-06-20 15:24:38.594194Z

因此,我的整个应用程序出现故障,消息的顺序变得很奇怪。如何解决这个问题?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您不需要自己存储时间戳。 Firestore 提供时间戳。见https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/FieldValue/serverTimestamp.html

    【讨论】:

    • 我使用的是实时数据库,而不是 Firestore。有没有办法在实时数据库中实现同样的效果?
    【解决方案2】:

    如果您使用的是 Firebase-Realtime 数据库,请使用此代码

    timeStamp = ServerValue.timestamp;
    

    如果您使用 Firestore,请使用此代码

    timeStamp = FieldValue.serverTimestamp();
    

    【讨论】:

      猜你喜欢
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多