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

How to save date in Angular as a timestamp to Firestore?

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

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

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

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

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: {};

angular 6 节点:8 RXJS 6.3.3 打字稿 2.9.2

如果您想在 Cloud Firestore 数据库中使用以下日期值:

firebase.firestore.FieldValue.serverTimestamp()

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

treatment.activationDate.toDate()

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

类型

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

但您可以在您的应用中使用 moment.js 来处理字符串。 moment('my date in a string format') 随心所欲转换。

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