如何在json_serializable flutter中将int时间戳转换为DateTime

时间:2019-03-24 20:06:56

标签: json dart flutter

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

示例代码

@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?

2 个答案:

答案 0 :(得分:2)

我用这个:

@JsonSerializable()
class Person {
  @JsonKey(fromJson: dateTimeFromTimestamp)
  DateTime dateOfBirth;
 
  ...
}

DateTime dateTimeFromTimestamp(Timestamp timestamp) {
  return timestamp == null ? null : timestamp.toDate();
}

答案 1 :(得分:0)

要将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 }'));