Alex Szum
Alex Szum

Reputation: 7

Can't add curent time into firebase firestore

I want to use current time to input in firebase firestore (timestamp). When I use the following code:

today: number = Date.now();

everything works fine, but time is updated only once (when a page is downloaded). So I did time update:

updatedTime(): void {
  setInterval(() => {
  this.today = new Date();
}, 1000);}

and then

ngOnInit() {
   this.updatedTime();
}

That works when I display time in the browser, but it doesn't work when I input _today into firebase firestore.

How to fix that?

Also there's a reason to use Date or better use timestamp that's provided by firebase apis?

Upvotes: 0

Views: 712

Answers (2)

Andy Fusniak
Andy Fusniak

Reputation: 1638

Not sure if I understood your question fully, but I use the built-in function firebase.firestore.FieldValue.serverTimestamp() to set the current timestamp whilst adding and updating.

Here is an example snippet...

const firebase = require('firebase');
const firestore = require('firebase/firestore');

// ...

let docRef = await this.db.collection('accounts').doc(accountId);
docRef.update({
  name,
  lastModified: firebase.firestore.FieldValue.serverTimestamp()
});

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317467

If you want a timestamp object in Firestore, you need to provide a Date object in the document you want to create or update, such as new Date(). Don't use a number value, such as the value returned by Date.now(), otherwise you will just see that number. This is true for each language binding with Firestore - they must each use their native Date type.

Upvotes: 1

Related Questions