5

I am trying to save personal info of person with birth date and activation date into Firestore database in Angular;

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()

Result in Firestore (not allowed to upload images sorry :) ):

activationDate: (map)
     _methodName: FieldValue.serverTimestamp 

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);

And a model:

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 Node: 8 rxjs 6.3.3 typescript 2.9.2

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

3 Answers3

5

If you want in your Cloud Firestore database the date value of:

firebase.firestore.FieldValue.serverTimestamp()

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()

This change was added in Firebase JS SDK v4.13.0, where JavaScript Date objects should be saved of type Timestamp.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
2

Since my date was converted into string at some point, I converted it back to Date object just before it is being saved to the database.

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

Just before I save it to firebase, I needed to convert it again to Date object.

// need to parse from String to Date
let myDateTemp = new Date(myDate);
record = {
    myDate: myDateTemp
}
return this.firestore.collection('myCollection').add(record);
Vince Banzon
  • 1,324
  • 13
  • 17
0

I save my data to firestore and use new Date(). The date is currently added as a timestamp to firestore.

But you can use moment.js in your app to handle the string. moment('my date in a string format') will be converted as you like.

1020rpz
  • 914
  • 10
  • 21