【问题标题】:How to save date in Angular as a timestamp to Firestore?如何将Angular中的日期作为时间戳保存到Firestore?
【发布时间】:2019-04-19 12:51:59
【问题描述】:

我正在尝试将具有出生日期和激活日期的人的个人信息保存到 Angular 的 Firestore 数据库中;

但是,传递带有Date() 类型字段的对象,日期被保存为字符串:

this.treatment.activationDate = new Date();
// gives such result in firestore with string type
// activationDate: "2018-11-16T09:48:51.137Z"

也尝试使用服务器时间戳,但是下面的方法没有返回有效值:

firebase.firestore.FieldValue.serverTimestamp()

Firestore 中的结果(不允许上传图片,抱歉 :)):

activationDate: (map)
     _methodName: FieldValue.serverTimestamp 

但是,此方法无法为我提供自定义日期的时间戳(例如birthDate) 那么使用 Angular 将日期保存为 Firestore 中的时间戳对象的最佳方法是什么?

.....
import  * as firebase from 'firebase';
.....
export class AddPatientComponent implements OnInit { 
......

this.treatment.activationDate = new Date();
  //firebase.firestore.FieldValue.serverTimestamp();
  console.log("timestamp: ", this.treatment.activationDate,                  firebase.firestore.FieldValue.serverTimestamp()); 
  this.patientService.savePatient(this.patient, this.treatment,   this.courseMeds);

还有一个模型:

export class CourseMed{
  amountPerDay: number;
  atc: String;
  name: String;
  days: number;
  dosage: number;
  form: String;
  method: String;
  periodicity: number;
  takeTimes: string[];
  used: number;
  takenCount: {};

角度 6 节点:8 rxjs 6.3.3 打字稿 2.9.2

【问题讨论】:

    标签: javascript angular firebase google-cloud-firestore angularfire2


    【解决方案1】:

    如果您希望 Cloud Firestore 数据库中的日期值是:

    firebase.firestore.FieldValue.serverTimestamp()
    

    您应该调用.toDate() 函数。请从官方文档中查看FireStore Timestamp 以获取更多信息。在您的特定情况下,您应该使用以下调用:

    treatment.activationDate.toDate()
    

    此更改是在 Firebase JS SDK v4.13.0 中添加的,其中 JavaScript Date 对象应保存为 Timestamp 类型。

    【讨论】:

      【解决方案2】:

      由于我的日期在某个时候被转换为字符串,所以我在将其保存到数据库之前将其转换回 Date 对象。

      let myDate = new Date();
      // myDate is converted to string at some point.
      

      就在我将其保存到 firebase 之前,我需要再次将其转换为 Date 对象。

      // need to parse from String to Date
      let myDateTemp = new Date(myDate);
      record = {
          myDate: myDateTemp
      }
      return this.firestore.collection('myCollection').add(record);
      

      【讨论】:

        【解决方案3】:

        我将数据保存到 Firestore 并使用 new Date()。该日期当前作为时间戳添加到 Firestore。

        但您可以在应用程序中使用 moment.js 来处理字符串。 moment('my date in a string format') 将根据需要进行转换。

        【讨论】:

          猜你喜欢
          • 2020-02-09
          • 2019-12-02
          • 1970-01-01
          • 2021-12-31
          • 1970-01-01
          • 2018-06-22
          • 2019-09-13
          • 2018-08-13
          • 2020-08-10
          相关资源
          最近更新 更多