aryan singh
aryan singh

Reputation: 827

How to print Firestore timestamp as formatted date and time

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'

Upvotes: 43

Views: 61949

Answers (16)

krishnaacharyaa
krishnaacharyaa

Reputation: 24920

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()

Upvotes: 1

CopsOnRoad
CopsOnRoad

Reputation: 267474

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

Upvotes: 2

Timestamp t = document['time'] // Timestamp(seconds=1624653319,nanoseconds=326000000)
DateTime d = t.toDate();
print(d.toString()); //2021-06-25 18:48:48.364

Upvotes: 1

Vivek
Vivek

Reputation: 494

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.

Upvotes: 4

Aashar Wahla
Aashar Wahla

Reputation: 3295

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.

Upvotes: 1

Mr. FORTAS
Mr. FORTAS

Reputation: 598

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)

Upvotes: 1

Martinho Mussamba
Martinho Mussamba

Reputation: 467

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);
  }

Upvotes: 0

Sophie-Timezonedesign
Sophie-Timezonedesign

Reputation: 17

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);

Upvotes: 0

CEO tech4lifeapps
CEO tech4lifeapps

Reputation: 895

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

Upvotes: 2

cNhecka
cNhecka

Reputation: 21

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;

Upvotes: 0

Ashutosh Singh
Ashutosh Singh

Reputation: 1277

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

Upvotes: 11

Bharath
Bharath

Reputation: 1166

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

Upvotes: 28

Jaycee
Jaycee

Reputation: 9

Do like so:

DateFormat.yMMMd().add_jm().format(DateTime.parse(snapshot.data.documents[index].data['timestamp'].toDate().toString())]

Upvotes: 0

Sushil Maurya
Sushil Maurya

Reputation: 625

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())

Upvotes: 50

Shyju M
Shyju M

Reputation: 9933

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 !

Upvotes: 6

worldpotato
worldpotato

Reputation: 51

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

Upvotes: 1

Related Questions