我有一个实例,DateTime我想将其格式化为String.我怎么做?我想把日期变成一个字符串,比如"2013-04-20".
我想从 Firestore 获取会议并将它们映射到以下Meeting模型中:
part 'meeting.g.dart';
@JsonSerializable(explicitToJson: true)
class Meeting {
String id;
DateTime date;
Meeting(this.id, this.date);
factory Meeting.fromJson(Map<String, dynamic> json) {
return _$MeetingFromJson(json);
}
Map<String, dynamic> toJson() => _$MeetingToJson(this);
}
Run Code Online (Sandbox Code Playgroud)
文档是从 Firestore 获取的,然后fromJson在可迭代对象上调用,但会引发异常:
type 'Timestamp' is not a subtype of type 'String' in type cast
Run Code Online (Sandbox Code Playgroud)
当我进入 generate 时meeting.g.dart,正是这一行导致了错误
json['date'] == null ? null : DateTime.parse(json['date'] as String)
Run Code Online (Sandbox Code Playgroud)
为了解决此问题,我尝试将模型中的 DateTime 更改为 Timestamp,但随后显示以下构建错误:
Error running JsonSerializableGenerator
Could not generate `fromJson` code for `date`.
None of the …Run Code Online (Sandbox Code Playgroud) 如何将 firestore 时间戳更改为“2 天前或 1 小时前”之类的内容?我尝试直接显示它,但出来的数据是像Timestamp(seconds=1556459022, nanosecond=0).
怎么做?