繁体   English   中英

如何将 firebase 中的时间戳数据类型转换为日期?

[英]How to convert timestamp data type in firebase to date?

我的 firebase 数据库中有这个。 开始日期:2018 年 12 月 25 日下午 4:00:00 UTC-8。 我希望它随时间转换为日期。

我试过了,但没用

{{ (elem.beginDate*1000) | 日期 }}。

我正在 Ionic 上构建一个应用程序,我的模板有这段代码。

来自:{{(elem.beginDate*1000 | 日期)}}

给出输出 [object Object]

Firestore 时间戳不会以数字形式返回。 它们是时间戳对象。 如果要将时间戳转换为 JavaScript 日期,请使用其toDate()方法。

首先从 firebase 检索时间戳,然后使用 toDate() 将时间戳转换为日期。 您还可以使用 toMillis()。 有关更多信息: 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);
    })
})

我从 Firestore 得到的是:t {seconds: 1622775600, nanoseconds: 0}

这就是我能够将其转换为日期格式的原因:

  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};
        })
    }));

我希望这对你有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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