我正在从集合
中获取数据。我以 timestamp
Firestore 标准格式保存了日期。这就是我保存 record['entryDate'] = firebase.firestore.FieldValue.serverTimestamp();
现在,当我获取它时,我希望它在数组中的新变量中采用可读格式。这是我当前用于获取数据的代码:
home.ts
ngOnInit {
//start fetch
this.crudService.read_Projects().subscribe(data => {
this.projectList = data.map(e => {
return {
id: e.payload.doc.id,
isEdit: false,
name: e.payload.doc.data()['name'],
desc: e.payload.doc.data()['desc'],
followers: e.payload.doc.data()['followers'],
milestone: e.payload.doc.data()['milestone'],
entryDate: e.payload.doc.data()['entryDate'],
// for each readable_entryDate = how do i convert ?
};
})
console.log(this.projectList);
});//end fetch
}
crud.service.ts
read_Projects() {
return this.firestore.collection('projects').snapshotChanges();
}
我可以使用 get()
来做到这一点,但无法在上面的代码中做到这一点,以防您希望查看我的 get()
获取代码并将日期转换为可读格式:
const ref = firebase.firestore().collection('cities').where('name', '==', 'JALANDHAR')
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
const timeinmillsecs = doc.data().timestamp.seconds * 1000; //1. get timestamp and make it in milli
console.log(new Date(timeinmillsecs)); // 2. convert to time lambi string
let a1 = new Date(timeinmillsecs); // 3. convert to simple date
let show_year_month_date = a1.getFullYear()+'/'+(a1.getMonth()+1) +'/'+a1.getDate(); // 3.convert to imple date
console.log(show_year_month_date); // 4. needed result // will show this on form
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
编辑 1
使用ToDate()
后,将我的代码更改为
entryDate: e.payload.doc.data()['entryDate'].toDate(),
我正在获取完整的 JS 日期对象,但我只需要日期,可能在数组中的 entryDate2
字段中,我该如何实现?
以下是日期现在的情况:
最佳答案
这不是必需的:
doc.data().timestamp.seconds * 1000
您只需调用toDate()即可在 Timestamp 对象上获取 JavaScript 日期。
之后,您可能想考虑使用诸如 momentjs 之类的库。根据用户的区域设置和偏好设置日期格式。
关于javascript - 在 Firestore 中将时间戳转换为可读日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61390116/