Udeesha Induwara
Udeesha Induwara

Reputation: 615

How to save Date as Timestamp in Angular Firestore?

firestore.Timestamp.now();

I tried this way and it saves date as map.

nanoseconds: 388000000
seconds: 1570897877

nanoseconds and seconds type are number.

I want to save date as firestore timestamp using angular. I found duplicate questions without accepted answer.

Upvotes: 4

Views: 8242

Answers (3)

Kunso Solutions
Kunso Solutions

Reputation: 7630

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.

Upvotes: 2

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

Upvotes: 4

user4991547
user4991547

Reputation:

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

Upvotes: 1

Related Questions