【问题标题】:How to save data as Firestore Timestamp object in Angular如何在 Angular 中将数据保存为 Firestore Timestamp 对象
【发布时间】:2019-04-21 16:09:45
【问题描述】:

只想将日期保存为 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);
}  

【问题讨论】:

  • 我认为这是因为打字稿日期实际上是以 unix 时间显示的。您可以添加 |日期管道到您的视图,如果这是您需要的,可以在那里转换它?
  • 它正在视图中工作,但我想将日期字符串保存为 Firestore 数据库中的时间戳。

标签: angular typescript firebase google-cloud-firestore angular6


【解决方案1】:
  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 获取一个月的原因。

【讨论】:

    【解决方案2】:

    我在 Firebase 中使用时间戳,我知道它用于将日期存储在 long 中,这是数字。所以我不知道Firestore中是否相同。

    【讨论】:

      猜你喜欢
      • 2019-02-27
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多