Skip to content Skip to sidebar Skip to footer

Get New Date In Cloud Functions In Specific Time Zone

I am trying to get my local date time in Cloud Functions using new Date(), but the result is with offset + 3. Is there any way to get the correct offset? Without convert, using ne

Solution 1:

A JavaScript Date object just represents a point in time for all people on the planet, without respect to timezone. If you print the Date object, you will see a timezone, but that's just because the code that renders the date is using the timezone of the clock configured on the computer. It's still the same point in time not matter what computer the date, or what timezone it's configured for.

If you want to format the date for people in a specific timezone, you will have to write some code for that. A common library to help with that is momentjs, using its timezone plugin.

Solution 2:

Cloud Functions run in GMT timezone, regardless of the environment's actual location. If you want the date/time in a specific timezone, you will have to convert it to that timezone yourself in your code.

Solution 3:

Here is the method I created for Cloud Functions, hope it helps:

functiondatetimeLocal(timezone : number) : Date {
    const localdate = newDate(Date.parse(newDate().toLocaleString('en-US', { timeZone: 'UTC' })) + (timezone * 60 * 60 * 1000));
    return localdate;
 }

Then you can just call this function, passing the desired local timezone, eg.: datetimeLocal(-3) and you'll receive a new Date() object according to the timezone you need.

I repeat, for it to work, DONT NEED TO CHANGE THE STRINGS 'en-US' neither 'UTC'.

Post a Comment for "Get New Date In Cloud Functions In Specific Time Zone"