41

My timestamp returns Timestamp(seconds=1560523991, nanoseconds=286000000) in a Flutter Firestore snapshot.

I want to print it as properly formatted date and time.

I'm using DateTime.now() to store current DateTime in Firestore while creating new records and retrieving it using Firestore snapshot but I am not able to convert to into formatted date time. I'm using lib intl.dart for formatting.

Code for saving data

       d={'amount':amount,
      'desc':desc,
      'user_id':user_id,
      'flie_ref':url.toString(),
      'date':'${user_id}${DateTime.now().day}-${DateTime.now().month}-${DateTime.now().year}',
      'timestamp':DateTime.now()
return Firestore.instance.collection('/data').add(d).then((v){return true;
    }).catchError((onError)=>print(onError));
    });

Accessing with 

    FutureBuilder(
                  future: Firestore.instance
                      .collection('data')
                      .where('user_id', isEqualTo:_user_id)
                      .getDocuments(),
                  builder: (BuildContext context,
                      AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (!snapshot.hasData)
                      return Container(
                          child: Center(child: CircularProgressIndicator()));
                    return ListView.builder(
                        itemCount: snapshot.data.documents.length,
                        itemBuilder: (BuildContext context, int index) {
                          return Column(
                            children: <Widget>[
       Text(DateFormat.yMMMd().add_jm().format(DateTime.parse(snapshot.data.documents[index].data['timestamp'].toString())]);


....

Error thrown is

Invalid date format.

I'm expecting output is: 'Jan 17, 2019, 2:19 PM'

David Buck
  • 3,752
  • 35
  • 31
  • 35
aryan singh
  • 807
  • 2
  • 8
  • 18

16 Answers16

49

When we push the DateTime object to Firestore, it internally converts it to it's own timestamp object and stores it.

Method to convert it back to Datetime after fetching timestamp from Firestore:

Firestore's timestamp contains a method called toDate() which can be converted to String and then that String can be passed to DateTime's parse method to convert back to DateTime

DateTime.parse(timestamp.toDate().toString())
Sushil Maurya
  • 615
  • 6
  • 4
  • 16
    I think we don't first need to convert the timestamp.toDate() to string and then parse the string to get the actual DateTime. You can simply do timestamp.toDate(). It already returns the DateTime. – Ashutosh Singh Apr 06 '20 at 16:46
  • "parse" doesn't exist...? I did this - myDate = DateFormat('dd-MMM-yy ~ HH:mm').format(data['itemDate'].toDate()).toString(), – Wesley Barnes Feb 28 '21 at 13:26
25

Here is way!

Firestore will return TimeStamp like Timestamp(seconds=1560523991, nanoseconds=286000000).

This can be parsed as

Timestamp t = document['timeFieldName'];
DateTime d = t.toDate();
print(d.toString()); //2019-12-28 18:48:48.364
Bharath
  • 1,036
  • 10
  • 13
  • 1
    .toDate() is a Timestamp function. Timestamp is provided by Firebase cloud firestore not by default flutter material.Try by import 'package:cloud_firestore/cloud_firestore.dart'; – Bharath May 03 '20 at 09:44
  • getDateTimeFromTimestamp(int timestampInSeconds) { var date = DateTime.fromMillisecondsSinceEpoch(timestampInSeconds * 1000); return date; } DateTime lastPostedMessageOnDateTime = getDateTimeFromTimestamp(document['timeFieldName'].seconds); It worked for me. Thanks. – Kamlesh Jun 15 '21 at 17:44
9

You can directly convert the Firestore timestamp object to DateTime like this:

DateTime myDateTime = (snapshot.data.documents[index].data['timestamp']).toDate();

This will return your Firestore timestamp in the dart's DateTime format. In order to convert your DateTime object you can use DateFormat class from intl package. You can use your obtained DateTime object to get the format of your choice like this:

DateFormat.yMMMd().add_jm().format(myDateTime);

This code produces an output like this:

Apr 21, 2020 5:33 PM
Ashutosh Singh
  • 1,107
  • 17
  • 28
6

timestamp parameter is the time in seconds

String formatTimestamp(int timestamp) {
      var format = new DateFormat('d MMM, hh:mm a');
      var date = new DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
      return format.format(date);
    }

Please check this answer for intl date formats

Hope it helps !

Shyju M
  • 9,387
  • 4
  • 43
  • 48
  • for formatTimestamp() to pass I m not getting data in int type, i m getting data as Timestamp(seconds=1560523991, nanoseconds=286000000) this format – aryan singh Jun 17 '19 at 10:01
4

I found Ashutosh's suggestion gives more user friendly output. A function like this is recommended in a helper class with a static method.

  static convertTimeStamp(Timestamp timestamp) {
    assert(timestamp != null);
    String convertedDate;
    convertedDate = DateFormat.yMMMd().add_jm().format(timestamp.toDate());
    return convertedDate;
  }

Intl package is require for DateFormat.

Vivek
  • 437
  • 5
  • 12
2

Once you've got a timestamp back from Firestore, something like

Timestamp(seconds=1560523991, nanoseconds=286000000)

you need to parse it into an object of type DateTime:

DateTime myDateTime = DateTime.parse(timestamp.toDate().toString());

 print('$myDateTime');

This will give you something like:

2020-05-09 15:27:04.074

You can then format myDateTime like this:

String formattedDateTime =
          DateFormat('yyyy-MM-dd – kk:mm').format(myDateTime);

print('$formattedDateTime');

That will give you:

2020-05-09 – 15:27

CEO tech4lifeapps
  • 885
  • 1
  • 12
  • 31
2

Use intl package:

Timestamp firebaseTimestamp = ...;
var date = firebaseTimestamp.toDate();

var output1 = DateFormat('MM/dd, hh:mm a').format(date); // 12/31, 10:00 PM
var output2 = DateFormat.yMMMd().format(date); // Dec 31, 2000
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
1

You will get a unix timestamp from firestore even if you send a DateTime to firestore.

You can parse a DateTime from Firestore with DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);

The DateTime class has two option to return a sting. toIso8601String() or toString() choose the one you need. Or use eg. DateTime.now().hour; to get the our and create your own output.

For more information: Check https://api.dartlang.org/stable/2.4.0/dart-core/DateTime-class.html

1

Using cloud firestore, Here's my what worked for me:

Text(snapshot.data["YouKey"].toDate().toString().substring(0,16))

subString is optionnal, I've added it because I had the clock time with many number after the minute (like 12:00 00:00:00)

Mr. FORTAS
  • 558
  • 5
  • 3
1

It took a long time to find the perfect answer. When you fetch the data from Firestore as a Timestamp object and you are sure about that then I will recommend you use the following code:

DateTime fetchedDate = e.data()["deadline"]?.toDate();

using ?.toDate() worked for me and hopefully will also work for you.

Aashar Wahla
  • 2,785
  • 1
  • 13
  • 19
1
Timestamp t = document['time'] // Timestamp(seconds=1624653319,nanoseconds=326000000)
DateTime d = t.toDate();
print(d.toString()); //2021-06-25 18:48:48.364
Mohammad Nazari
  • 2,535
  • 1
  • 18
  • 29
  • 3
    Give some description to explain your code. Have a look on [How to answer](https://stackoverflow.com/help/how-to-answer). – a.ak Jun 29 '21 at 10:25
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – B001ᛦ Jun 30 '21 at 11:32
0

Do like so:

DateFormat.yMMMd().add_jm().format(DateTime.parse(snapshot.data.documents[index].data['timestamp'].toDate().toString())]
csabinho
  • 1,579
  • 1
  • 18
  • 28
Jaycee
  • 9
  • 1
0

First visit here for intl package, then paste the package into your pubspec.yaml, run pub get (the usual way of updating pubspec).Import the package into your dart file and try out the below method.

String timestamp;

DateTime now = DateTime.now();
String formatDate =
    DateFormat('yyyy-MM-dd – kk:mm').format(now);
timestamp = formatDate;
cNhecka
  • 21
  • 2
0

You should use fromMillisecondsSinceEpoch function.

var d = new DateTime.fromMillisecondsSinceEpoch(ts, isUtc: true);

Here ts is int type.

So we can convert Firebase timestamps to DateTime object as follows.

DateTime date = DateTime.fromMillisecondsSinceEpoch(timestamp.seconds * 1000);
0

Simple way to solve it.

//Declare a variable Timestamp and assign the value timestamp from database

Timestamp timestamp = document['timeFieldName'];

//Use DateTime's parse method to convert back to DateTime

DateTime _time =DateTime.parse(timestamp.toDate().toString())

//Use this method to get the H:m of the DateTime. //You can choose the DateFormat you want.

String readTimeStamp(DateTime date)
  {
    
     var format =new DateFormat.Hm(); // My Format 08:00

     return format.format(date);
  }
0

There are different ways this can be achieved based on different scenario, see which of the following code fits your scenario.

Conversion of Firebase timestamp to DateTime:

  1. document['timeStamp'].toDate()
    
  2. (document["timeStamp"] as Timestamp).toDate()
    
  3. DateTime.fromMillisecondsSinceEpoch(document['timeStamp'].millisecondsSinceEpoch);
    
  4. Timestamp.fromMillisecondsSinceEpoch(document['timeStamp'].millisecondsSinceEpoch).toDate();
    
  5. If timeStamp is in microseconds use:

    DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000000);
    
  6. If timeStamp is in milliseconds use:

    DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
    
  7. Add the following function in your dart file.

     String formatTimestamp(Timestamp timestamp) {
       var format = new DateFormat('yyyy-MM-dd'); // <- use skeleton here
       return format.format(timestamp.toDate());
     }
    

call it as formatTimestamp(document['timestamp'])


Note: To print this DateTime append toString()
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88