Search code examples
node.jsfirebasegoogle-cloud-functions

How to set the timezone in a Cloud Storage trigger? (Cloud Functions 2nd gen for Firebase)


Is there a way in the 2nd generation of Cloud Function to set a different timezone inside a Cloud Storage Trigger?

I have a trigger that generates and optimize images, it is a long process, but I'd share to you the relevant for this post. Take this example code

export const resizeImage = onObjectFinalized({
  region: 'southamerica-east1'
}, async (event: CloudEvent<StorageObjectData>) => {
  const fileBucket = event.data.bucket;
  const filePath = event.data.name as string;
  const contentType = event.data.contentType as string;
  try {
  /* Long process that generates a new image, stores the new image, 
 deletes the original and saves its download url to Firestore... */
  } catch(e) {
  // If error, save it in Firestore.
  const errorDocData = {
            timestamp: Date.now(),
            errorCode: e.errorCode || '',
            stack: e.stack || '',
            context: { filePath: event.data.name, bucket: event.data.bucket },
            message: e.message
        }
   const colRef = firestore.collection(`Procesos/ProcesoOptimizarImagen/Errors`)
   await colRef.add(errorDocData)
}
})

The relevant is that I want to store a datetime when an error occurs. I'd like to set the timezone of this cloud function to "Argentina/Buenos Aires" since is the place where the system is being used.

Another relevant information is that I'm interested in querying these errors ordered by datetime, for example, the app will get the most resent errors first.


Solution

  • Firestore timestamps don't have a timezone. They are just two numbers that describe the amount of time since the unix epoch in UTC. JavaScript Date objects are very similar - they are just a single number representing about the time point in time. To repeat: there are no timezones involved the creation, computation, or ordering of a Date or Timestamp - any timezone you see is just a rendering of that point in time using a timezone as a point of reference.

    If you print a Timestamp (or Date object) and see a timezone, that is just an interpretation the local computer's clock for the timezone where it is configured. It has no bearing on the actual numbers that represent the point in time.

    Even if you could change the timezone for a Cloud Functions instance (you can't), that wouldn't change anything about the Date or Timestamp objects you're using. Your queries would all work exactly the same way.

    See also: