How to add timestamp on document create to Firestore from Flutter

Viewed 8407

I am writing code to set data to Firestore from flutter. What I want is to add a field for the time the data is created, eg "createdOn". DateTime.now() for Flutter takes the time from the device but I would like to get the serverside time. My code is as below:

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

It would be a great help if I could have a field like below that gets the timestamp for firebase.

   'createdOn' : TimestampHere,
3 Answers

You can use the FieldValue.serverTimestamp()

serverTimestamp(): FieldValue Returns a sentinel used with set() or update() to include a server-generated timestamp in the written data.

'createdOn':FieldValue.serverTimestamp()

References

you can use several types of time stamp ,example date time

"timestamp": DateTime.now(),

server value

'timestamp' : Timestamp.now()

If you are using Firebase,you should store the timestamp from epoch like that

DateTime.now().microsecondsSinceEpoch
Related