user2828442
user2828442

Reputation: 2525

Convert timestamp to readable date in Firestore

I am fetching data from collection. I saved date in timestamp Firestore standard format. This is how I am saving record['entryDate'] = firebase.firestore.FieldValue.serverTimestamp();

Now when I am fetching it, I want it to be in the readable format in a new variable in array. This is the code I am currently using to fetch the data:

home.ts

ngOnInit {
        //start fetch
        this.crudService.read_Projects().subscribe(data => {
          this.projectList = data.map(e => {
            return {
              id: e.payload.doc.id,
              isEdit: false,
              name: e.payload.doc.data()['name'],
              desc: e.payload.doc.data()['desc'],
              followers: e.payload.doc.data()['followers'],
              milestone: e.payload.doc.data()['milestone'],
              entryDate: e.payload.doc.data()['entryDate'],

             // for each readable_entryDate =  how do i convert ?

            };
          })
          console.log(this.projectList);
        });//end fetch
}

crud.service.ts

  read_Projects() {
    return this.firestore.collection('projects').snapshotChanges();
  }

enter image description here

I am able to do it using get() but unable to do it in the above code, in case you wish to see my get() code for fetching and converting date to readable format:

 const ref = firebase.firestore().collection('cities').where('name', '==', 'JALANDHAR')
 .get()
 .then(function(querySnapshot) {
   querySnapshot.forEach(function(doc) {
   const timeinmillsecs = doc.data().timestamp.seconds * 1000; //1. get timestamp and make it in milli
   console.log(new Date(timeinmillsecs)); // 2. convert to time lambi string
   let a1 = new Date(timeinmillsecs); // 3. convert to simple date
   let show_year_month_date =  a1.getFullYear()+'/'+(a1.getMonth()+1) +'/'+a1.getDate(); // 3.convert to imple date
   console.log(show_year_month_date); // 4. needed result // will show this on form
 });
 })
 .catch(function(error) {
     console.log("Error getting documents: ", error);
 });

Edit 1

After using ToDate(), changing my code to

entryDate: e.payload.doc.data()['entryDate'].toDate(),

I am getting full JS date object, but I need only date, maybe in entryDate2 field in my array, how can I achieve that?

Below is how date is coming now:

enter image description here

Upvotes: 0

Views: 376

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317928

This isn't necessary:

doc.data().timestamp.seconds * 1000

You can simply call toDate() on a Timestamp object to get a JavaScript Date.

After that, you might want to look into using a library such as momentjs to format the date according to the user's locale and preferences.

Upvotes: 1

Related Questions