How to recover the time (HH: MM) timestamp stored in Cloud Firestore?
How to recover the time (HH: MM) timestamp stored in Cloud Firestore?
I have a problem
I am saving a datetime with:
created_at: firebase.firestore.FieldValue.serverTimestamp(),
I'm trying to retrieve the time, by reading each doc:
renderMensaje: function(msj) {
var date = new Date(msj.data().created_at * 1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = date.getMinutes();
date = hours + ":" + minutes;
// ...
But, it doesn't work right.
console.log(date); // => Wed Dec 31 1969 18:00:00 GMT-0600 (hora estándar central)
console.log(msj.data().created_at);
// => Timestamp(seconds=1535222867, nanoseconds=351000000)
How can I get the time (HH:MM)?
Looks like an Unix-timestamp. You can parse it into a Date object and from that get hours/minutes: stackoverflow.com/a/847196/7362396
– Tobias K.
Aug 25 at 19:49
2 Answers
2
Firestore stores dates in documents as a Timestamp type object. If you want to get a Date object from a timestamp field in the document, you'll have to use its toDate() method to convert it.
Issue - Firestore returns a Timestamp object
Resolution - Convert msj.data().created_at
to JS Date object using toDate()
msj.data().created_at
Code Snippet
renderMensaje: function(msj)
var date = msj.data().created_at.toDate();
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = date.getMinutes();
date = hours + ":" + minutes;
Also, check MomentJs. It is a lightweight, simple date library for parsing, manipulating, and formatting dates.
Something is wrong: console.log(date); // => Wed Dec 31 1969 18:00:00 GMT-0600 (hora estándar central)
– David Betancourt M.
Aug 25 at 20:23
This would be the result of
new Date(your_timestamp)
, use prototype functions on the date
object as mentioned above.– mehtankush
Aug 25 at 20:47
new Date(your_timestamp)
date
created_at
is a Timestamp object, not a number.– Doug Stevenson
Aug 25 at 21:38
created_at
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Please mention what is it that is not working? Read stackoverflow.com/help/how-to-ask for more points
– mehtankush
Aug 25 at 19:47