how to print Firestore timestamp as formatted date and time in flutter

别说谁变了你拦得住时间么 提交于 2020-03-22 09:14:44

问题


timestamp return aa Timestamp(seconds=1560523991, nanoseconds=286000000) in flutter firestore snapshot

I want to print it 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 it returning format I notable convert to into formatted date time, for formatting I m using lib intl.dart

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 throwing is Invalid date format.

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


回答1:


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



回答2:


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 !




回答3:


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




回答4:


Do like so:

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



回答5:


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


来源:https://stackoverflow.com/questions/56627888/how-to-print-firestore-timestamp-as-formatted-date-and-time-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!