Reputation: 369
I am an interface where I have declared lastLogin as Date.
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
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