如何将整数时间戳转换为日期时间。
示例代码:
@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?
答案 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 }'));