简体   繁体   中英

Firebase firestore query by datetime show different results depending of the timezone of the phone Flutter

I am having a problem with timezone when saving and querying bettwing dates on firebase firestore. I wanna save the dates without matter about the timezone just like (2022-12-31 00:00:00.000), but when i do this on the client side depending of the timezone it saves on a different day, and query result different data too.

How do i do this independent of the timezone? i mean if the user is on UTC+4 or UTC-4 it does not change the day or hour when saving, just save (2022-12-31 00:00:00.000) on the firestore database? Somehow i do not understand it is querying and saving based on the local timezone i guess.

Thanks in advance.

Use Firebase's TimeStamp while adding data to the firebase

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. It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one. It is encoded assuming all minutes are 60 seconds long, ie leap seconds are "smeared" so that no leap second table is needed for interpretation.

To access timeStamp use FieldValue.serverTimestamp()

Usage

Add data
_firestore
.collection('post')
.add({
   'text': postText,
   'created': FieldValue.serverTimestamp()  // 👈 This timestamp is independent of the timezone
});
Query data
_firestore.
.collection('post')
.orderBy('created', descending: false)    // 👈 Data will be same irrespective of access point
.snapshots()                          

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM