简体   繁体   中英

Convert date object to Firestore timestamp

I'm trying to convert a date object to a Firestore timestamp.

var dateOBJ = new Date(); 
var timeStamp = new firebase.firestore.Timestamp(dateOBJ);

This gives me an error:

Uncaught Error: Timestamp seconds out of range: Sun Dec 09 2018 11:37:05 GMT+0100

I tried converting the date object to seconds first by using .getTime() / 1000, but it's still out of range.

The timestamp is gonna be the expiration date for an url, so I need to add some time to it.

You won't get a consistent server side timestamp with a JavaScript date. Instead, send the server timestamp from the SDK:

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

If you still want to set the timestamp as a Date you can just pass new Date() to Firestore and it will be saved as a timestamp.

Frank is right about setting timestamps into firestore.

If you want to check that timestamp on the front end afterwards you need to use .toDate on the timestamp object returned from firestore to turn it back into a JS date.

There are two ways of setting a date field in Cloud Firestore:

  1. You specify a Date value for the field, in which case you fully determine what date is written.
  2. You specify the firebase.firestore.FieldValue.serverTimestamp() , in which case the server writes the current date.

There is no way in the API to combine these two options, you either use one or the other.

Since you comment that you want to store the timestamp and an offset, that is also what I'd store:

  • a timestamp field that you let the server populate with firebase.firestore.FieldValue.serverTimestamp() .
  • a offset field, that you populate from the app with the offset in days/hours.

That way you can reconstitute the effective expiration timestamp by combining the two fields.


You could even add a third field that stores the expiration timestamp, but that will require an extra write operation. I'd typically do this in Cloud Functions, to ensure you keep full control over the field and clients can't spoof it. If you don't do it in Cloud Functions, consider writing security rules that validate that the value if the calculated field is indeed the result of that calculation.

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