【问题标题】:How to convert int timestamp to DateTime in json_serializable flutter如何在 json_serializable 颤振中将 int 时间戳转换为 DateTime
【发布时间】:2019-08-15 02:52:14
【问题描述】:

如何将整数时间戳转换为日期时间。

示例代码:

@JsonSerializable(nullable: false)
class Person {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth;
  Person({this.firstName, this.lastName, this.dateOfBirth});
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
  Map<String, dynamic> toJson() => _$PersonToJson(this);    
}  

如何将 dateOfBirth 整数 timeStamp 转换为 DateTime?

【问题讨论】:

    标签: json dart flutter


    【解决方案1】:

    要将int 时间戳转换为DateTime,您需要传递一个静态方法 将DateTime 结果返回给@JsonKey 注解中的fromJson 参数。

    此代码解决了问题并允许转换。

    @JsonSerializable(nullable: false)
        class Person {
          final String firstName;
          final String lastName;
          @JsonKey(fromJson: _fromJson, toJson: _toJson)
          final DateTime dateOfBirth;
          Person({this.firstName, this.lastName, this.dateOfBirth});
          factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
          Map<String, dynamic> toJson() => _$PersonToJson(this);
    
          static DateTime _fromJson(int int) => DateTime.fromMillisecondsSinceEpoch(int);
          static int _toJson(DateTime time) => time.millisecondsSinceEpoch;
    
        }   
    

    用法

    Person person = Person.fromJson(json.decode('{"firstName":"Ada", "lastName":"Amaka", "dateOfBirth": 1553456553132 }'));
    

    【讨论】:

    • 在我的来自 firebase 的案例数据中,它对我不起作用,时间戳值到 datetime(local) 失败。
    【解决方案2】:

    我用这个:

    @JsonSerializable()
    class Person {
      @JsonKey(fromJson: dateTimeFromTimestamp)
      DateTime dateOfBirth;
     
      ...
    }
    
    DateTime dateTimeFromTimestamp(Timestamp timestamp) {
      return timestamp == null ? null : timestamp.toDate();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 2021-01-12
      • 2018-10-16
      • 2023-03-04
      • 2020-05-12
      • 2020-07-09
      • 2016-08-23
      • 2021-11-08
      • 2020-10-09
      相关资源
      最近更新 更多