0

I am using ionic 4 and firebase for a project and everything is going great except for the dates. I started seeing warnings in the console that Date() will break in the future and that firebase should use timestamp to store datetimes.

For things like a created at or modified at time, I can use:

createdAt: firebase.firestore.FieldValue.serverTimestamp()

and it will successfully store the current date/time as a timestamp into firebase.

However, trying to pass a specific date/time as a timestamp doesn't seem to work. I have a reactive form and in it is an ionic date picker. The HTML is

<ion-item>
<ion-label>Date/Time:</ion-label>
    <ion-datetime formControlName="date" displayFormat="YYYY MMM DD @ HH:mm"></ion-datetime>
</ion-item>

and the typescript then has a reactive form created with all the control names and validators. When the form is submitted I call an async function which sends everything to firebase.

  async create() {
const id = this.game ? this.game.id : '';
const data = {
  createdAt: firebase.firestore.FieldValue.serverTimestamp(),
  ...this.game,
  ...this.gameForm.value,
};
this.db.updateAt(`games/${id}`, data);
this.modal.dismiss();

}

However the date in the ionic datepicker is sent as a map instead of a timestamp. It has year/month/hour/etc. objects instead of a single timestamp.

enter image description here

The ionic docs show the date picker as being in ISO format. Anyone know why this happens or how I can convert it to a timestamp?

  • I'm not a firebase expert - but wrote this answer that helped a lot of people. Wondered if you could use something from this. https://stackoverflow.com/a/45330707/495157 – JGFMK Feb 28 '19 at 15:52

1 Answers1

-1

I figured it out. Using a JS Date() firestore should automatically convert to a timestamp when stored. I just had grab the value from the form and adjust it to be a date AFTER the spread syntax.

async create() {
const id = this.game ? this.game.id : '';
const data = {
  createdAt: firebase.firestore.FieldValue.serverTimestamp(),
  ...this.game,
  ...this.gameForm.value,
  date: new Date(this.gameForm.value.date)

};
this.db.updateAt(`games/${id}`, data);
this.modal.dismiss();

}