Datetime 从Dart向Cloud Firestore写入时间戳

Datetime 从Dart向Cloud Firestore写入时间戳,datetime,flutter,dart,google-cloud-firestore,timestamp,Datetime,Flutter,Dart,Google Cloud Firestore,Timestamp,我正在尝试将DateTime作为时间戳写入Cloud Firestore,如果我尝试添加一个列表,则该日期将在Firestore中以字符串值显示 例如,如果我有一个用户类: class User { final String name; final DateTime birthday; User(this.name, this.birthday) } 我是这样写的: Firestore.instance.collection("users").add({ "name":use

我正在尝试将DateTime作为时间戳写入Cloud Firestore,如果我尝试添加一个
列表
,则该日期将在Firestore中以字符串值显示

例如,如果我有一个
用户
类:

class User {
  final String name;
  final DateTime birthday;

  User(this.name, this.birthday)
}
我是这样写的:

Firestore.instance.collection("users").add({
  "name":user.name, 
  "date":Timestamp.fromDate(user.birthday)
})
Firestore.instance.collection("users").add(user.toMap())
它工作正常,并且日期作为时间戳类型正确地显示在Firestore中

但是,如果我尝试创建一个
映射
并添加它:

class User {
  ...
  Map<String, dynamic> toMap() {
    return {
      "name": name,
      "date": Timestamp.fromDate(birthday)
    }
  }
}
然后它在Firestore中显示为字符串,而不是时间戳


有人知道为什么吗?

试试
FieldValue.serverTimestamp()
既然你说
日期:Timestamp.fromDate(user.birth)
有效,为什么你不能使用它呢?@spall将时间戳设置为服务器上的当前时间,这显然不是我想要做的。我想写一个生日。@FrankvanPuffelen我可以,但我喜欢在对象类中有一个
toJson()
函数的整洁。@odiggity很抱歉我误解了。试试
FieldValue.serverTimestamp()
既然你说
“date”:Timestamp.fromDate(user.birth)
有效,为什么你不能使用它呢?@这会将时间戳设置为服务器上的当前时间,这显然不是我想要做的。我正试图写一个生日。@FrankvanPuffelen我可以,但我喜欢在对象类中有一个
toJson()
函数的整洁。@odiggity抱歉我误解了这一点。