如何在Angular中将日期保存为Firestore的时间戳?

时间:2018-11-16 10:34:16

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

我正在尝试将具有 出生日期和激活日期 的人的个人信息保存到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) 那么使用角度将日期保存为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

3 个答案:

答案 0 :(得分:1)

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

firebase.firestore.FieldValue.serverTimestamp()

您应该使用对.toDate()函数的调用。另请参阅FireStore Timesteamp官方文档以了解更多信息。在您的特定情况下,您应该使用以下调用:

treatment.activationDate.toDate()

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

答案 1 :(得分:0)

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

但是您可以在应用程序中使用moment.js来处理字符串。 moment(“我的日期格式为字符串格式”)会根据需要进行转换。

答案 2 :(得分:0)

由于我的日期在某个时候被转换为字符串,因此在将其保存到数据库之前,我将其转换回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);
相关问题