My timestamp returns Timestamp(seconds=1560523991, nanoseconds=286000000)
in a Flutter Firestore snapshot.
I want to print it as properly formatted date and
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);
}
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
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
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 !
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
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.