Javascript 如何将 Firestore 日期/时间戳转换为 JS Date()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/52247445/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a Firestore date/Timestamp to a JS Date()?
提问by blueether
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,
我正在尝试将以下日期转换为 javascript Date() 对象。当我从服务器取回它时,它是一个 Timestamp 对象,
Screenshot from Firebase Firestore console:
Firebase Firestore 控制台的屏幕截图:
When I try the following on a list of objects returned from firestore:
当我对从 firestore 返回的对象列表尝试以下操作时:
  list.forEach(a => {
    var d = a.record.dateCreated;
    console.log(d, new Date(d), Date(d))
  })
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?
显然,时间戳全都不同,并且与 2018 年 9 月 9 日(恰好是今天)的日期不同。我也不确定为什么会new Date(Timestamp)导致invalid date. 我是一个 JS 新手,我在日期或时间戳上做错了吗?
回答by Doug Stevenson
The constructor for a JavaScript Date doesn't know anything about Firestore Timestampobjects - it doesn't know what to do with them.
JavaScript Date 的构造函数对 Firestore Timestamp对象一无所知- 它不知道如何处理它们。
If you want to convert a Timestamp to a Date, use the toDate()method on the Timestamp.
如果要将时间戳转换为日期,请使用时间戳上的toDate()方法。
回答by Naman Sharma
Please use toDate() method and then convert it into the format using angular pipe like this -
请使用 toDate() 方法,然后使用像这样的角管将其转换为格式 -
{{ row.orderDate.toDate() | date: 'dd MMM hh:mm' }}
{{ row.orderDate.toDate() | 日期:'dd MMM hh:mm' }}
回答by Dilshan Liyanage
How to convert Unix timestamp to JavaScript Date object.
如何将 Unix 时间戳转换为 JavaScript 日期对象。
var myDate = a.record.dateCreated;
new Date(myDate._seconds * 1000); // access the '_seconds' attribute within the timestamp object
回答by Nagibaba
At last, I could get what I need. This returns date as 08/04/2020
终于,我可以得到我需要的东西了。这将返回日期为08/04/2020
new Date(firebase.firestore.Timestamp.now().seconds*1000).toLocaleDateString()
回答by Wajahath
You can use Timestamp.fromDateand .toDatefor converting back and forth.
您可以使用Timestamp.fromDate和.toDate用于来回转换。
// Date to Timestamp
const t = firebase.firestore.Timestamp.fromDate(new Date());
// Timestamp to Date
const d = t.toDate();


