如何在json_serializable flutter中将int时间戳转换为DateTime [英] How to convert int timestamp to DateTime in json_serializable flutter
本文介绍了如何在json_serializable flutter中将int时间戳转换为DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将整数时间戳转换为日期时间。
How can I convert an integer timestamp to Datetime.
示例代码:
@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?
How do I convert dateOfBirth integer timeStamp to DateTime?
推荐答案
要将 int
时间戳转换为 DateTime
,您需要传递一个静态方法,使
向 fromJson $返回
DateTime
结果。 @JsonKey批注中的c $ c>参数。
To convert an int
timestamp to DateTime
, you need to pass a static method that
returns a DateTime
result to the fromJson
parameter in the @JsonKey annotation.
此代码解决了该问题并允许进行转换。
This code solves the problem and allows the convertion.
@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 }'));
这篇关于如何在json_serializable flutter中将int时间戳转换为DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文