Laurent Maquet
Laurent Maquet

Reputation: 400

Retrieving a date from Firestore in Node.js

From the Firestore documentation on saving data of supported types, I red:

var docData = {
    //...
    dateExample: new Date("December 10, 1815"),
    //...
    }
};
db.collection("data").doc("one").set(docData).then(function() {
console.log("Document successfully written!");
});

This is what I use in my Cloud Functions to save various dates to Firestore. It works great !

My problem comes when I need to retrieve those dates and post them as String to a third party API.

As far as I understood, in Firebase/Firestore, dates are stored as a Unix Timestamp.

I couldn't find anywhere (firebase doc, stackoverflow ...) how to convert it properly to a String.

I tried unsuccessfully the following:

function timeConverter(UNIX_timestamp){
    var a = new Date(UNIX_timestamp * 1000);
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    var year = a.getFullYear();
    var month = months[a.getMonth()];
    var date = a.getDate();
    var hour = a.getHours();
    var min = a.getMinutes();
    var sec = a.getSeconds();
    var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
    return time;
  }

admin.firestore().collection('users').doc(userId).get()
    .then( (doc) => {
        const user = doc.data();
        const birthDate = user.birthDate;
        const birthDateString = timeConverter(birthDate);
        console.log(`birthDateString =${birthDateString}`);
     // "birthDateString = NaN undefined NaN NaN:NaN:NaN" 
     });

Upvotes: 2

Views: 3392

Answers (2)

NULL SWEΔT
NULL SWEΔT

Reputation: 2037

First you can use toDate() to convert the Firebase timestamp to a Date object and then use the Date's object method toDateString() to convert it to a String.

const birthDate = user.birthDate.toDate();
const birthDateString = birthDate.toDateString();

You can also check out Moment.js, it helps a lot when dealing with Dates and displaying them.

Upvotes: 9

Ronnie Smith
Ronnie Smith

Reputation: 18565

This boils down to : how do I convert a unix timestamp to a human readable date?

There are several ways to do this but one of the easiest is to use

var readableData = new Date(doc.data().myUnixTimestamp).toLocaleDateString("en-US");

There are options for all locales. See MDN's Date.prototype.toLocaleDateString.

Upvotes: 0

Related Questions