I have a Cloud Function that resets the date of a document field on Cloud Firestore, but with the hours segment of the Timestamp set to midnight.
This resets at midnight every day from the client side, where the Cloud Function itself is triggered.
The Cloud Function, however, is setting the date to be one hour ahead of the expected date. I.e., if the real date is 29 March 2022 at 00:00:00 UTC 1, the Cloud Function is setting it to be 29 March 2022 at 01:00:00 UTC 1.
I can't use the a serverside timestamp as this doesn't allow any days to be added to it via the Cloud Function, which is necessary for my use case, as I'm sometimes resetting the date for a week ahead on latter parts of the function.
Before the change to UTC 1 yesterday, the Cloud Function was functioning correctly and was updating the date to the expected date and time (i.e. to midnight).
So far I get the day set to midnight from this:
const today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
I then update the document via this:
return ref.doc(doc.id).update({
"Next Date Due": admin.firestore.Timestamp.fromDate(today)
});
CodePudding user response:
Firestore timestamps don't have a timezone encoded into them. It just stores the offset from the Unix epoch using a combination of seconds and nanoseconds (which are fields on the Timestamp object).
If you view a timestamp field in the Firestore console, you will see the time displayed in the local timezone that your computer uses from its local settings. For example, I have a local timezone on my system that is UTC 8, If I update the object field "Next Date Due"
, Firestore console will show March 29, 2022 at 8:00:00 AM UTC 8
as it reflects the timezone on my system as shown on the screenshot below.
You could try to fetch the time after updating to double check:
const today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
console.log('today:', today);
ref.doc(doc.id).update({
"Next Date Due": admin.firestore.Timestamp.fromDate(today)
})
.then(() => {
ref.doc(doc.id).get().then((doc) => {
if (doc.exists) {
console.log("Document data:", doc.data()["Next Date Due"].toDate());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch((error) => {
console.log("Error getting document:", error);
});
});
This will result to:
today: 2022-03-29T00:00:00.000Z
Document data: 2022-03-29T00:00:00.000Z
If you want to render a Date object for a specific timezone, I would suggest for you to use a library such as moment.js.