[英]Retrieving a date from Firestore in Node.js
From the Firestore documentation on saving data of supported types, I red: 从有关存储受支持类型的数据的Firestore文档中 ,我将看到红色:
var docData = {
//...
dateExample: new Date("December 10, 1815"),
//...
}
};
db.collection("data").doc("one").set(docData).then(function() {
console.log("Document successfully written!");
});
This is what I use in my Cloud Functions to save various dates to Firestore. 这就是我在Cloud Functions中用于将各种日期保存到Firestore的用途。 It works great !
它很棒!
My problem comes when I need to retrieve those dates and post them as String to a third party API. 当我需要检索这些日期并将其作为字符串发布到第三方API时,就会出现我的问题。
As far as I understood, in Firebase/Firestore, dates are stored as a Unix Timestamp. 据我了解,在Firebase / Firestore中,日期存储为Unix时间戳。
I couldn't find anywhere (firebase doc, stackoverflow ...) how to convert it properly to a String. 我找不到任何地方(firebase文档,stackoverflow ...)如何将其正确转换为String。
I tried unsuccessfully the following: 我尝试以下操作失败:
function timeConverter(UNIX_timestamp){
var a = new Date(UNIX_timestamp * 1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
return time;
}
admin.firestore().collection('users').doc(userId).get()
.then( (doc) => {
const user = doc.data();
const birthDate = user.birthDate;
const birthDateString = timeConverter(birthDate);
console.log(`birthDateString =${birthDateString}`);
// "birthDateString = NaN undefined NaN NaN:NaN:NaN"
});
First you can use toDate()
to convert the Firebase timestamp to a Date
object and then use the Date
's object method toDateString()
to convert it to a String. 首先,您可以使用
toDate()
将Firebase时间戳转换为Date
对象,然后使用Date
的对象方法toDateString()
将其转换为String。
const birthDate = user.birthDate.toDate();
const birthDateString = birthDate.toDateString();
You can also check out Moment.js , it helps a lot when dealing with Dates and displaying them. 您还可以查看Moment.js ,它在处理日期并显示它们时会很有帮助 。
This boils down to : how do I convert a unix timestamp to a human readable date? 归结为:如何将Unix时间戳转换为人类可读的日期?
There are several ways to do this but one of the easiest is to use 有几种方法可以做到这一点,但最简单的方法之一就是使用
var readableData = new Date(doc.data().myUnixTimestamp).toLocaleDateString("en-US");
There are options for all locales. 所有语言环境都有选项。 See MDN's Date.prototype.toLocaleDateString .
参见MDN的Date.prototype.toLocaleDateString 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.