如何将整数时间戳转换为日期时间。
示例代码:
@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);
}
Run Code Online (Sandbox Code Playgroud)
如何将 dateOfBirth 整数 timeStamp 转换为 DateTime?
non*_*hto 12
要将int时间戳转换为DateTime,您需要将返回DateTime结果的静态方法传递给fromJson@JsonKey 注释中的参数。
此代码解决了问题并允许转换。
@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;
}
Run Code Online (Sandbox Code Playgroud)
用法
Person person = Person.fromJson(json.decode('{"firstName":"Ada", "lastName":"Amaka", "dateOfBirth": 1553456553132 }'));
Run Code Online (Sandbox Code Playgroud)
我用这个:
@JsonSerializable()
class Person {
@JsonKey(fromJson: dateTimeFromTimestamp)
DateTime dateOfBirth;
...
}
DateTime dateTimeFromTimestamp(Timestamp timestamp) {
return timestamp == null ? null : timestamp.toDate();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3582 次 |
| 最近记录: |