Reputation: 8642
Anyone knows how to persist UTC Timestamp in Firestore?
In my Angular
app, if I convert today's date to a Timestamp like the following and I end up with a UTC+2
(it's summer time here right now in Switzerland) date in the Firestore database
import {firebase} from '@firebase/app';
import '@firebase/firestore';
const myTimestamp = firebase.firestore.Timestamp.fromDate(new Date());
If for example I try to convert a date from the winter time, I end up with UTC+1
Timestamp in the database
const myTimestamp = firebase.firestore.Timestamp.fromDate(new Date(2019, 0, 1));
If I would use now()
I end up with UTC+2
dates too
const now: firebase.firestore.Timestamp = firebase.firestore.Timestamp.now();
I don't do anything particular when I persist the data:
const now: firebase.firestore.Timestamp = firebase.firestore.Timestamp.now();
const myTimestamp = firebase.firestore.Timestamp.fromDate(new Date());
const myData = {
created_at: now,
another_value: myTimestamp
};
await this.collection.add(myData);
Any idea how is it possible to create valid UTC
Timestamp for Firestore?
Upvotes: 14
Views: 16905
Reputation: 101
Part of the confusion, at least for me, was caused by how the Firebase Console displays the saved timestamps as "March 21th 2024 at 10:52:34 UTC+1" and "July 15th 2023 at 13:30:30 UTC+2", making it seem like there's a distinction between these two time zones.
But Doug Stevenson above is right, Firebase does not save time zone. So why UTC+1 and UTC+2? The display converts the times into the right timezone for the viewer, and for countries with daylight savings time, this means that there will be two different time zones used depending on whether the timestamp is in summer or in winter! But in the background, it's all UTC.
Upvotes: 2
Reputation: 317352
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). Most date/time objects are like this - they don't care what the timezome is, it's just an absolute point in time.
If you view a timestamp field in the console, you will see the time displayed in the local timezone that your computer uses from its local settings.
If you convert a timestamp to a JavaScript Date object, that date object naturally renders itself in the browser's local timezome, similar to the console.
If you want to render a Date object for a specific timezone, you should use a library to do that for you, such as moment.js.
Upvotes: 26