最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get new Date in Cloud Functions in specific time zone - Stack Overflow

programmeradmin5浏览0评论

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 new Date().getTimezoneOffset

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 new Date().getTimezoneOffset

Share Improve this question edited Nov 27, 2019 at 9:26 Jose V 1,5061 gold badge6 silver badges12 bronze badges asked Nov 22, 2019 at 14:40 edilson14edilson14 231 silver badge3 bronze badges 6
  • Can you provide the output? – keser Commented Nov 22, 2019 at 14:44
  • What do you mean by "local" date time? Your puter timezone? – Freez Commented Nov 22, 2019 at 14:56
  • @aomerk 2019-11-25T11:18:56 , but the correct output should be 2019-11-25T08:18:56 – edilson14 Commented Nov 25, 2019 at 11:23
  • @Freez my location , brazilian – edilson14 Commented Nov 25, 2019 at 11:24
  • @edilson14 get IP address from request and you can than use IP addresses location to get correct Date, if it is what you want. If you only want to output Brazilian look up localeString and how to use it – keser Commented Nov 25, 2019 at 11:28
 |  Show 1 more ment

3 Answers 3

Reset to default 7

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.

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 puter. It's still the same point in time not matter what puter 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 mon library to help with that is momentjs, using its timezone plugin.

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

function datetimeLocal(timezone : number) : Date {
    const localdate = new Date(Date.parse(new Date().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'.

发布评论

评论列表(0)

  1. 暂无评论