【问题标题】:TimeStamp to DateTime conversion Firebase to FlutterTimeStamp 到 DateTime 转换 Firebase 到 Flutter
【发布时间】:2021-05-30 02:02:49
【问题描述】:

直奔主题。我是 Firebase Firestore 的新手。

我有模特:


     @JsonSerializable()
      class CategoryEntity extends Equatable {
       final String id;
       final String name;
       @JsonKey(fromJson: _fromJson, toJson: _toJson)
       final DateTime createdDate;
       @JsonKey(fromJson: _fromJson, toJson: _toJson)
       final DateTime updatedDate; 
       final String description;

    const CategoryEntity(
      this.id,
      this.name,
      this.createdDate,
      this.updatedDate,
      this.description,
    );

要保存在 Firebase Firestore 中的数据是 createDateupdatedDate 的时间戳。

但问题是我无法将数据从 Firebase 转换为本地数据。 save 方法将dateCreate 转换为时间戳罚款。

     static DateTime _fromJson(int int) =>
        DateTime.fromMillisecondsSinceEpoch(int);
      static int _toJson(DateTime time) => time.millisecondsSinceEpoch;

请提供任何解决方案。

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    据我了解,您希望将 ServerTimeStamp 显示给用户本地时间。

    我有两种方法可以检查,

    使用这个包timeformatter的人,会根据用户的时间告诉你时间。

    A mini truth table for the format of the value returned by the function:
    < 1 second : "Just now"
    < 60 seconds : "X seconds" (2-59)
    < 2 minutes : "1 minute"
    < 60 minutes : "X minutes" (2-59)
    < 2 hours : "1 hour"
    < 24 hours : "X hours" (2-23)
    < 2 days : "1 day"
    < 7 days : "X days" (2-6)
    < 2 weeks : "1 week"
    < 28 days : "X weeks" (2-3)
    < 30.44 * 1.5 days : "1 month"
    < 365 - 15.22 days : "X months" (2-12)
    < 730 days : "1 year"
    Rest: "X years"
    

    二、可以用这个包改一下intl

    import 'package:intl/intl.dart';
    
    int timeInMillis = 1586348737122; //no need to convert it just set the timestamp here.
    var date = DateTime.fromMillisecondsSinceEpoch(timeInMillis);
    var formattedDate = DateFormat.yMMMd().format(date); //
    

    您可以在此帖子中查看答案以获取更多信息Dart/Flutter : Converting timestamp

    【讨论】:

    • 谢谢!但问题仍然存在,无法将时间戳转换为日期时间。发生异常。这主要发生在 Firebase Firestore 集合中,将数据保存为时间戳。
    猜你喜欢
    • 1970-01-01
    • 2015-04-20
    • 2020-12-15
    • 2022-01-02
    • 1970-01-01
    • 2016-10-30
    • 2012-11-22
    相关资源
    最近更新 更多