简体   繁体   中英

Date format for Firebase Firestore

Here's my problem: I want to send a timestamp to a firestore document. I was previously using a package called "react-native-datetime-picker", which returned a UNIX Epoch timestamp which I would directly send to firestore using:

 startsAt: new firebase.firestore.Timestamp(startsAt, 83000000),
 endsAt: new firebase.firestore.Timestamp(endsAt, 83000000),

(startsAt and endsAt being the timestamps). This worked and would send a timestamp to firestore, however, due to the fact that on Android you can only choose either date or time to pick and not both simulteanously, I am now using a packaged named "react-native-modal-datetime-picker" which allows me to pick both. Now this package returns a fully-fletched date in this format:

2021-03-20T18:25:00.000Z

When I try to send this to firestore, it doesn't work while saying: FirebaseError: Timestamp seconds out of range. So I am guessing that I'm trying to send a non-conventional format of date to Firestore. Is there any way to change this date to a timestamp? Or is there another workaround for this situation? Thanks in advance !

I managed to send the date to Firestore using the getTime() function:

startsAt: new firebase.firestore.Timestamp(Math.round(startsAt.getTime() / 1000), 83000000),

getTime() transforms your date into an epoch timestamp in milliseconds, which you divide by 1000 to get in seconds and make sure Firestore stores it as a timestamp. You have to round it, as Timestamp() can't take decimals as parameters.

 const timestamp = firebase.firestore.FieldValue.serverTimestamp();

Did you try this method, this is built-in firestore method and work properly across the all timestamps

Reference: https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue

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