Flutter Cloud Firestore convert serverTimestamp to String

3,240

When you read a timestamp from a document in Cloud Firestore you get back a Timestamp object.

To convert this to a regular date object, you can call the toDate() method on it.

And then you can format that Date object in any way you'd usually do, e.g. with the DateFormat class as shown in Date Time format in Flutter dd/MM/YYYY hh:mm

Share:
3,240
tonik
Author by

tonik

Updated on December 14, 2022

Comments

  • tonik
    tonik over 1 year

    My flutter app needs to get the current Time, I already tried several packages for this like: truetime, ntptime, Datetime from dart, Timestamp.now from cloud firestore they were all returning different times when switching the timezone in the phone settings. The only method were it was returning the same time for all devices on all time zones was the FieldValue.serverTimestamp() method, Im saving this value into a firestore document and there it recognizes it as a Field of Type Timestamp.

    I want to convert this into a String so that I get a String like this: "year-month-day hours:minutes:seconds"

    what I tried:

    (1)

    final now = FieldValue.serverTimestamp();
    

    saving this now variable into a document ... , document field looks like this:

    timestamp: Day.Month Year at Hours:Minutes:Seconds UTC+2 (Timestamp)

    then Im taking this value from the field "timestamp" and assign it to a text widget:

    Text(doc.data["timestamp"].toString())
    

    Text Widget looks like this:

    Timestamp(seconds=1568560057, nanoseconds=790000000)

    what it should like(as already said):

    "year-month-day hours:minutes:seconds"

    (2)

    final now = FieldValue.serverTimestamp().toString();
    

    saving this now variable into a document ... , document field looks like this:

    timestamp: "Instance of 'FieldValue'" (String)

    then Im taking this value from the field "timestamp" and assign it to a text widget:

    Text(doc.data["timestamp"].toString())
    

    Text Widget looks like this:

    Instance of 'FieldValue'

    what it should like(as already said):

    "year-month-day hours:minutes:seconds"


    So anyone knows how I can get the String format I need or maybe another method which is returning same time for all devices and time zones and which is convertable into a String of the format I need?

    Thanks in advance!


    SOLUTION: Thanks to Frank and CopsOnRoad

    We have to save this value into a document field:

    final now = FieldValue.serverTimestamp();
    

    this will be saved as a Timestamp object in the document field.

    now we need to convert it to a DateTime Object for using it in a Text Widget for example and then convert this to a String to get the format:

    Text(doc.data["timestamp"].toDate().toString())
    

    Text Widget looks like this:

    Year-Month-Day Hours:Minutes:Seconds

    solved.