Ken
Ken

Reputation: 1481

How to handle dates on Firestore?

From what I understand, when you store a date:

const date = firebase.firestore.Timestamp.fromDate(new Date())

You are storing a date object in the local timezone. However, when I later read this date from Firestore using:

doc.data().date.toDate()

This gives me the date in UTC, instead of the local timezone. Is this the expected behaviour? Am I understanding this correctly? It seems like it would make more sense to retrieve the date in local time since the date you stored is in local time.

Upvotes: 0

Views: 760

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

When you store a date (in Firestore) with firebase.firestore.Timestamp.fromDate(new Date()), you are storing a date object in the local timezone.

This is actually not correct: All timestamps in Firestore are saved in UTC. The timezone of the user who saved the timestamp is not saved with the timestamp value.

Is this the expected behaviour?

Yes, storing the value in UTC gives the maximum flexibility for the developer to display it as desired, depending on his specific requirements.

As a matter of fact, it's up to the developer to display it with the timezone he wants when displaying it in a frontend. For example, the Firebase console converts the UTC date the timezone to which your computer is configured.

Upvotes: 1

Related Questions