如何将 Firestore 日期/时间戳转换为 JS Date()? [英] How do I convert a Firestore date/Timestamp to a JS Date()?

查看:37
本文介绍了如何将 Firestore 日期/时间戳转换为 JS Date()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将以下日期转换为 javascript Date() 对象.当我从服务器取回它时,它是一个 Timestamp 对象,

I am trying to convert the below date to a javascript Date() object. When I get it back from the server, it is a Timestamp object,

Firebase Firestore 控制台的屏幕截图:

当我对从 firestore 返回的对象列表尝试以下操作时:

When I try the following on a list of objects returned from firestore:

  list.forEach(a => {
    var d = a.record.dateCreated;
    console.log(d, new Date(d), Date(d))
  })

我得到这个输出:

显然,时间戳全都不同,并且与 2018 年 9 月 9 日(恰好是今天)的日期不同.我也不确定为什么 new Date(Timestamp) 会导致 无效日期.我是一个 JS 新手,我是不是在日期或时间戳上做错了什么?

Clearly the Timestamps are all different, and are not all the same date of Sept 09, 2018 (which happens to be today). I'm also not sure why new Date(Timestamp) results in an invalid date. I'm a bit of a JS newbie, am I doing something wrong with the dates or timestamps?

推荐答案

JavaScript Date 的构造函数对 Firestore 一无所知 Timestamp 对象 - 它不知道如何处理它们.

The constructor for a JavaScript Date doesn't know anything about Firestore Timestamp objects - it doesn't know what to do with them.

如果要将时间戳转换为日期,请使用 toDate() 时间戳上的方法.

If you want to convert a Timestamp to a Date, use the toDate() method on the Timestamp.

这篇关于如何将 Firestore 日期/时间戳转换为 JS Date()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆