Newaj
Newaj

Reputation: 4450

What is the perfect way of storing date in firestore?

I'm using flutter. In which way a DateTime should be stored in firestore so that I can make a filter based on the DateTime. Should it be converted to String or something else? What is the perfect way here?

Upvotes: 1

Views: 2577

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599001

Firestore has a native Timestamp type that can be used to store timestamps, which:

A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time

This type is perfectly suited for filtering on date/time ranges, for example when you want to get all documents with a field between January 7, 2021 at 7:41:00AM and January 20, 2021 at 2:00:42PM.

In cases where I'm purely interested in a date and not in a time, I often store that as a string in "20210107" format (so yyyyMMdd). I find this format slightly easier when I want to get documents for a specific date, as I can use an equality filter. But the trade-off is that I love the precision of time. As you can probably guess from my phrasing this is a personal preference, not necessarily a best way for all cases or everyone.

Upvotes: 7

Mert Toptas
Mert Toptas

Reputation: 114

It must be a string, you can split or format it as the day / month / year you want after the string value

Upvotes: 0

Related Questions