My Cloud firestore has TimeStamp data, I am fetching it and displaying it in a datatable widget. To covert it to desired date format, I Used DateFormat('yMd').Format()
. But format() only accepts datetime and not timestamp. So, to convert firebase timestamp data to date time I used TimeStamp().toDate()
. but TimeStamp() accepts seconds and nanoseconds. I tried providing firebase timestamp data in this format data['paidDate']
I get error, How do I fix this.
return Center(
child: Container(
child: DataTable(
columns: const [
DataColumn(label: Text('Ammount')),
DataColumn(label: Text('Paid Date'))
],
rows: snapshot.data!.docs.map((data) {
// DateTime datee = data['paidDate'];
return DataRow(cells: [
DataCell(Text(data['amount'])),
DataCell(Text(DateFormat('yMd')
.format(Timestamp(data['paidDate']).toDate())))
]);
}).toList()),
));
CodePudding user response:
You need to write a converter function. Here is a example
///timestamp to date
static DateTime _dateTimeFromTimeStamp(Timestamp timestamp) => DateTime.parse(timestamp.toDate().toString());
CodePudding user response:
Firstly you need to convert the timestamp to DateTime and then you go to format the desired format date
DateTime date = DateTime.fromMillisecondsSinceEpoch(data['paidDate'] * 1000);
String formattedDate = DateFormat('yMd').format(date);
CodePudding user response:
var docs = Firebase.instance.doc(<id>).get();
Map<String, dynamic> data = docs.data!() as Map<String, dynamic>;
DateTime time = (data['timestamp'] as TimeStamp ).toDate();
Now time is of type DateTime. Pass it to .format()