Reputation: 476
I save the Map showen below to a firestore, but I want to save also a timestamp which should have the time and date a user picked with a date and time picker. The date is already in 'dd.MM.yyyy' formatted and the time is something like '6:58 PM'. The date is the variable date
and the time is the variable time
. How can I save a timestamp with the value time
and date
?
Map<String, dynamic> data = {
'name': userName,
'userUID': userUIDglobal,
'time: '//here I want to safe the timestamp
};
Firestore.instance
.collection('seller')
.document(documentID)
.collection('test')
.add(data);
}
Upvotes: 3
Views: 5476
Reputation: 2614
If you want to use server generated value which would be better so you don't depend on device time, use this:
Map<String, dynamic> data = {
'name': userName,
'userUID': userUIDglobal,
'time': FieldValue.serverTimestamp(),
};
Firestore.instance
.collection('seller')
.document(documentID)
.collection('test')
.add(data);
But pay attention that if you have an active collection snapshot subscription when you're writing this document to the collection you'll get one snapshot with null
value for time
(because of optimistic commit) and then when you get the data from the server you'll get the actual millisecond value.
EDIT: You can prevent the optimistic commit emitting null
value for the timestamp by doing this write as part of a transaction.
Upvotes: 9
Reputation: 329
I would suggest converting it to epoch time as int store it in your cloud and re-convert to DateTime after fetching it.
Example:
// Convert DateTime to int
int time = DateTime.now().millisecondsSinceEpoch;
Map<String, dynamic> data = {
'name': userName,
'userUID': userUIDglobal,
'time': time
};
// To safely convert it back to DateTime
DateTime fetchedTime = DateTime.fromMillisecondsSinceEpoch(data['time']);
Upvotes: 1