1

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

  • Please mention what is it that is not working? Read https://stackoverflow.com/help/how-to-ask for more points – nkshio Aug 25 '18 at 19:47
  • Looks like an Unix-timestamp. You can parse it into a Date object and from that get hours/minutes: https://stackoverflow.com/a/847196/7362396 – Tobias K. Aug 25 '18 at 19:49

2 Answers2

0

Issue - Firestore returns a Timestamp object

Resolution - Convert msj.data().created_at to JS Date object using toDate()


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.

nkshio
  • 1,060
  • 1
  • 14
  • 23
0

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.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441