ali262883
ali262883

Reputation: 369

Fetching timestamp from firestore Cloud Functions nodejs

I am an interface where I have declared lastLogin as Date.

LastLogin looks like this: enter image description here

export interface User {
 lastLogin: Date,
}

I am fetching this timestamp in my cloud function and I want it as a timestamp so that I can subtract it from the current Timestamp.

const mentor: User = mentorDoc.data() as User;
const login = mentor['lastLogin'];
const lastOpen  =  mentor['lastLogin'].valueOf();
const currentTime  = new Date().getTime();
const diffMs = (currentTime - lastOpen); 
const diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours

Last open shows like this :

063740174400.000000000

And when I use to like this :

const lastOpen  = new Date (mentor['lastLogin'].valueOf());

Output:

undefined

Upvotes: 1

Views: 89

Answers (1)

Christos Sirmakezis
Christos Sirmakezis

Reputation: 96

Please change Date to firestore Timestamp both in the interface declaration as well as the collection field that holds the date in the firestore console

export interface User {
  lastLogin: firebase.firestore.Timestamp,
}

You can now retrieve the date and also update it, this time simply by passing a new Date object.

// Read currently saved Timestamp
const ref = db.collection<User>('users').doc(`${uid}`).get().toPromise()
const saved_date = ref?.data().lastLogin
const current_date = new Date()

// if you just want the Date difference in ms after retrieving the timestamp from firestore.
const diff = current_date.getMilliseconds() - (saved_date.toDate()).getMilliseconds() // Timestamp -> Date (ms)

// Update Timestamp using a Javascript Date object
 db.collection('..').doc('..').set({ lastLogin: current_date }, {merge:true}) 

// set creates the field while update works only if field already exists

Upvotes: 2

Related Questions