【问题标题】:Converting fromMap millisecondsSinceEpoch to DateTime in dart在 dart 中将 fromMap millisecondsSinceEpoch 转换为 DateTime
【发布时间】:2017-01-31 16:33:43
【问题描述】:

我在 firebase json 中将 DateTime 存储为 millisecondsSinceEpoch,然后在调用 fromMap 时我想从 millisecondsSinceEpoch 进行转换。

除了我目前的方法之外,哪种方法最合适?

new DateTime.fromMillisecondsSinceEpoch(map['created_at'])

消息类

class Message {
  final String name;
  final String text;
  String photoURL;
  String imageURL;
  DateTime created_at;

  Message(this.name, this.created_at, [this.text, String photoURL, this.imageURL]) {
    this.photoURL = photoURL ??
        "https://lh3.googleusercontent.com/"
  }


  Message.fromMap(Map map) :
        this(map['name'], new DateTime.fromMillisecondsSinceEpoch(map['created_at']),  map['text'], map['photoURL'], map['imageURL']);


  Map toMap() =>
      {
        "name": name,
        "created_at": created_at.millisecondsSinceEpoch,
        "text": text,
        "photoURL": photoURL,
        "imageURL": imageURL
      };
}

【问题讨论】:

  • 你现在的使用方式有什么问题?

标签: json datetime angular firebase dart


【解决方案1】:

你的代码在我看来不错。

我可以看到您当前代码的唯一潜在问题是它在本地时区创建了 DateTime 对象。如果您希望它作为时间戳,您可能希望始终使用 UTC 时间,所以也许您希望:

new DateTime.fromMillisecondsSinceEpoch(map['created_at'], isUtc: true)

再一次,如果向用户显示日期,那么使用本地时间很可能是正确的做法。

另一个潜在的问题是地图可能包含一个字符串而不是一个数字,但您的示例在这里有一个数字,所以这可能不是问题。只需确保您知道 JSON 包含的内容即可。

(但对于 nitpick,created_at 成员通常在 Dart 中写为 createdAt)。

【讨论】:

    猜你喜欢
    • 2019-04-11
    • 2019-11-30
    • 2020-12-18
    • 2020-10-07
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    • 2021-03-26
    相关资源
    最近更新 更多