How to save Date as Timestamp in Angular Firestore?

Viewed 6751
3 Answers

If you want to add the current time as your Timestamp value in a Firestore document, you can you add it using FieldValue.serverTimestamp() as Doug mentioned, as in the following example:

import * as firebase from 'firebase';
[ . . . ]
db.collection('times').add({time: firebase.firestore.FieldValue.serverTimestamp()});

Should you want to get a specific time, you can create a new Date object and add it to your Firestore using the function toDateString() on it, as follows:

import * as firebase from 'firebase';
[ . . . ]
date = new Date('2018-11-16T09:48:51.137Z'); //sample date
this.db.collection('times').add({spec_time: this.date.toDateString()});
import * as firebase from 'firebase';

...


const data = {
    createdAt: firebase.default.firestore.FieldValue.serverTimestamp(),
};

This code worked for me. The important part was .default from the root firebase object.

You can use firebase.database.ServerValue.TIMESTAMP

Import firebase

import * as firebase from 'firebase';

Initialize it

firebase.initializeApp(environment.firebase);

then you can use

firebase.database.ServerValue.TIMESTAMP

To get the timestamp in milliseconds

Now, If you want to save the timestamp as Date then simply convert the timestamp by moment into your desired format and save it to the database

db.object("collection").set(moment(firebase.database.ServerValue.TIMESTAMP).toDate());
Related