【问题标题】:Convert Firestore timestamp into a date format将 Firestore 时间戳转换为日期格式
【发布时间】:2020-02-23 16:54:15
【问题描述】:

我有一项从 BehaviorSubject 获取某些数据的服务。

this.myData.album$.value.album_date;

当控制台记录从firestore返回的日期时:

console.log(this.myData.album$.value.album_date);

控制台显示:

Timestamp {seconds: 1572263054, nanoseconds: 63000000}

我需要做的是在我的一个函数中将此值转换为任何格式,例如“2019 年 10 月 28 日,星期一”。

不幸的是,鉴于我的要求,我不能在 HTML 中使用 toDate() |,这需要在我的函数中实现。

我们将不胜感激。

注意:我有 moment 可以在我的 Typescript 文件中使用。 我正在使用Angular 8Firestore

【问题讨论】:

    标签: typescript date google-cloud-firestore momentjs


    【解决方案1】:

    https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp#to-date

    您需要使用 Firebase 在您的函数中获取日期,然后将日期传递给您的 html:

    console.log(this.myData.album$.value.album_date.toDate());
    

    我觉得可以

    【讨论】:

    • 更新 - 这适用于开发环境。然而,'toDate()' 由打字稿用红色下划线。错误是Property 'toDate' does not exist on type 'Date'.ts(2339)。不幸的是,在生产环境中构建失败。
    【解决方案2】:

    聚会有点晚了,但我遇到了同样的问题。

    这是我的解决方案,虽然因为使用了any 而不是很漂亮,但它对我有用:

    (myAlbumDate as any).toDate()
    

    现在 TypeScript 不再抱怨,生产构建顺利通过。

    更新

    今天我发现自己处于同样的场景中,因为 any 类型让我头疼,我试图找到一个更优雅的解决方案,我在 another StackOverflow question 上找到了它,并将它应用到我的用例中。

    解决方案是像这样扩展Date接口:

    declare global {
      interface Date {
        toDate: () => Date;
      }
    }
    

    现在我有了 IntelliSense,并且不再有 any 或我的 Angular 模板中的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-26
      • 2019-02-25
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 2019-05-10
      • 2018-12-09
      相关资源
      最近更新 更多