简体   繁体   中英

How to convert timestamp data type in firebase to date?

I have this in my firebase database. beginDate: December 25, 2018 at 4:00:00 PM UTC-8. I want this to convert to Date with time.

I tried this and it is not working

{{ (elem.beginDate*1000) | date }}.

I am building an app on Ionic and my template has this code.

From: {{ (elem.beginDate*1000 | date) }}

which gives an output [object Object]

Firestore timestamps aren't returned as numbers. They're Timestamp objects. If you want to convert a Timestamp to a JavaScript Date, use its toDate() method.

First you retrieve the timestamp from firebase then you convert the timestamp to a date with toDate(). You can also use toMillis(). More information on: https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp.html#returnsnumber

db.collection('user').get().then( (snapshot) => {
    snapshot.docs.forEach(doc => {
        var time = doc.data().timestamp;
        var date = time.toDate();
        console.log(date);
    })
})

What I was getting from Firestore was this: t {seconds: 1622775600, nanoseconds: 0}

And this is what worked for me to be able to convert it to the date format:

  return this.collection.snapshotChanges().
     pipe(map(actions =>{
        return actions.map(item =>{
            const data = item.payload.doc.data() as [myObject];

            data.beginDate = new Date(data.beginDate["seconds"] * 1000);

            const id = item.payload.doc.id;
            return {...data,id};
        })
    }));

I hope this is useful to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM