如何在Angular中将日期保存为Firestore的时间戳? [英] How to save date in Angular as a timestamp to Firestore?
问题描述
我正在尝试将具有 出生日期和激活日期 的人的个人信息保存到Angular的Firestore数据库中;
I am trying to save personal info of person with birth date and activation date into Firestore database in Angular;
但是,传递具有Date()
类型字段的对象时,日期将保存为字符串:
However, passing object with Date()
type fields the dates are saved as a string:
this.treatment.activationDate = new Date();
// gives such result in firestore with string type
// activationDate: "2018-11-16T09:48:51.137Z"
也尝试使用服务器时间戳,但是以下方法未返回有效值:
Also tried to use server timestamp, but the following method does not return valid value:
firebase.firestore.FieldValue.serverTimestamp()
在Firestore中出现结果(抱歉,不允许上传图像:)):
Result in Firestore (not allowed to upload images sorry :) ):
activationDate: (map)
_methodName: FieldValue.serverTimestamp
但是,此方法无法为我提供自定义日期的时间戳(例如,birthDate) 那么使用角度将日期保存为Firestore中的时间戳对象的最佳方法是什么?
However, this method can not provide me a timestamp for custom dates (birthDate for example) So what is the best way to save date as a timestamp object in firestore using angular?
.....
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
angular 6 Node: 8 rxjs 6.3.3 typescript 2.9.2
推荐答案
如果要在Cloud Firestore数据库中使用以下日期值:
If you want in your Cloud Firestore database the date value of:
firebase.firestore.FieldValue.serverTimestamp()
您应该使用对 .toDate()<的调用/a>函数.请从官方文档中检出 FireStore时间戳以获得更多信息. .在您的特定情况下,您应该使用以下调用:
You should use a call to .toDate() function. Please checkout FireStore Timestamp from the official documentation for more information. In your particular case, you should use the following call:
treatment.activationDate.toDate()
此更改已添加到 Firebase JS SDK v4.13.0
,其中JavaScript Date
对象应保存为Timestamp
类型.
This change was added in Firebase JS SDK v4.13.0
, where JavaScript Date
objects should be saved of type Timestamp
.
这篇关于如何在Angular中将日期保存为Firestore的时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!