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

查看:126
本文介绍了如何将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日(恰好是今天)的相同日期。我也不确定为什么新日期(时间戳)导致无效日期。我是一个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日期对Firestore 时间戳对象一无所知 - 它我不知道如何处理它们。

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天全站免登陆