Can I add days to a Cloud Firestore server timestamp?

Viewed 1990

I am writing a React Native app that creates a coupon for a user that has a date created field as well as date expires in Firestore. The date expired is the date created plus some days (e.g 7)

Ideally I would like to use firestore.FieldValue.serverTimestamp() in my firebase function for the created plus add 7 days to this for the expiry to avoid having the user generate the date.

Is there a way for this to be done?

2 Answers

was running to the same issue, and the following code seems to work.

 const expiresIn = 7200
 const createdAt = admin.firestore.Timestamp.now().toDate()
 createdAt.setSeconds(createdAt.getSeconds() + expiresIn);
 admin.firestore.Timestamp.fromDate(createdAt)

When you tell Firestore to write a server timestamp, it does precisely that: it writes the timestamp of the server. There is no way to specify an offset for this operation.

This means you have broadly two options:

  1. Write the offset to a separate field in the same document. So you'd end up with two fields in the document: createdAt and expiresInDays.
  2. Read back the server timestamp and update it. This is typically something you'd do in Cloud Functions, when the document gets created functions.firestore.document('users/{userId}').onCreate((snap, context).
Related