如何将文档创建的时间戳从Flutter添加到Firestore

时间:2020-03-11 13:22:39

标签: firebase flutter google-cloud-firestore

我正在编写代码,以将数据设置为从flutter传递到Firestore。我想要的是在创建数据时添加一个字段,例如“ createdOn”。 Flutter的DateTime.now()从设备获取时间,但是我想获取服务器端时间。我的代码如下:

Future updateDataModel(String userName, String userPosition, String userLocation) async{
  return await userCollection.document().setData({
      'userName' : userName,
      'userPosition' : userPosition,
      'userLocation' : userLocation
    });
  }

如果我可以使用下面的字段来获取firebase的时间戳,那将是一个很大的帮助。

   'createdOn' : TimestampHere,

3 个答案:

答案 0 :(得分:3)

您可以使用FieldValue.serverTimestamp()

serverTimestamp():FieldValue返回与set()或 update()在写入的数据中包含服务器生成的时间戳。

'createdOn':FieldValue.serverTimestamp()

参考文献

答案 1 :(得分:0)

您可以使用几种类型的时间戳记,例如日期时间

"timestamp": DateTime.now(),

服务器值

'timestamp' : Timestamp.now()

答案 2 :(得分:0)

如果您使用的是Firebase,则应从这样的时代存储时间戳

DateTime.now().microsecondsSinceEpoch
相关问题