Lau*_*uet 2 node.js firebase google-cloud-functions google-cloud-firestore
从关于保存支持类型的数据的Firestore 文档中,我是红色的:
var docData = {
//...
dateExample: new Date("December 10, 1815"),
//...
}
};
db.collection("data").doc("one").set(docData).then(function() {
console.log("Document successfully written!");
});
Run Code Online (Sandbox Code Playgroud)
这是我在 Cloud Functions 中用于将各种日期保存到 Firestore 的方法。它很好用!
当我需要检索这些日期并将它们作为字符串发布到第三方 API 时,我的问题就出现了。
据我了解,在 Firebase/Firestore 中,日期存储为 Unix 时间戳。
我找不到任何地方(firebase doc,stackoverflow ...)如何将其正确转换为字符串。
我尝试了以下失败:
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"
});
Run Code Online (Sandbox Code Playgroud)
小智 8
首先,您可以使用toDate()
将 Firebase 时间戳转换为Date
对象,然后使用Date
的对象方法toDateString()
将其转换为字符串。
const birthDate = user.birthDate.toDate();
const birthDateString = birthDate.toDateString();
Run Code Online (Sandbox Code Playgroud)
您还可以查看Moment.js,它在处理日期和显示日期时有很大帮助。
归档时间: |
|
查看次数: |
2589 次 |
最近记录: |