首页 > 解决方案 > 如何在 Angular 中将数据保存为 Firestore 时间戳对象

问题描述

只想将日期保存为 Firestore 数据库中的时间戳,但它将时间戳存储为数字:

save() {
    const data = this.transactionForm.value;
    data.type = data.type == 'true' || data.type == true ? true : false;
    data.updated = firebase.firestore.FieldValue.serverTimestamp();
    // Date string to timestamp
    data.date =  new Date(data.date.split("-").reverse().join("-")).getTime();
    let id = data.id;
    this.transCollection.doc(id).update(data);
}  

标签: angulartypescriptfirebasegoogle-cloud-firestoreangular6

解决方案


  unixToTimestamp() {
    const date = new Date();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds =  date.getSeconds();
    const day = date.getDate();
    const month = date.getMonth() + 1;
    const year = date.getFullYear();

    console.log(hours + ':' + minutes + ':' + seconds);
    console.log(day + '/' + month + '/' + year);
  }

我在打字稿中尝试了这个,我得到了以下输出:

11:25:07
19/11/2018

通过这种方式,您可以选择创建时间戳并将其保存在 Firestore 中的方式

您也可以按照您想要的方式打印月份。

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

const month = months[date.getMonth()];

这是因为 date.getMonth() 获取索引,这就是我使用 +1 获取一个月的原因。


推荐阅读