Flutter: Firebase FieldValue.serverTimestamp() to DateTime object
The FieldValue.serverTimestamp()
is not a timestamp, but a so-called sentinel - a marker that gets sent to the server, that the server then recognizes and interprets to write the current timestamp. That means there is no way to convert FieldValue.serverTimestamp()
to a timestamp on the client.
What you can do is write FieldValue.serverTimestamp()
to a document on the server, and observe the value that is written to that document. This value will be a valid timestamp.
If you have as serverTimeStamp
field in your document you can convert it to DateTime
as follows;
final DateTime dateTimeFromServerTimeStamp =
(documentSnapshot.data()['serverTimeStamp'] as Timestamp).toDate();
Assuming you used serverTimeStamp in firebase, and you're reading it back you can read the timestamp read from firebase using DateTime.parse() :
DateTime timestamp = DateTime.parse( json['ts'].toString() );