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

javascript - Invoking toLocaleString() in UTC - Stack Overflow

programmeradmin3浏览0评论

I have a variable d of type Date and value '2017-05-01T01:00:00.000Z'.

My time zone is UTC-4.

When I invoke:

 d.toLocaleString("en-US", { month: "short" });

I get Apr, because the date is Apr 30, 2017 2100h UTC-4 where my Javascript is running.

Is there an easy way to get toLocaleString to treat the date instance according to its UTC equivalent?

I have a variable d of type Date and value '2017-05-01T01:00:00.000Z'.

My time zone is UTC-4.

When I invoke:

 d.toLocaleString("en-US", { month: "short" });

I get Apr, because the date is Apr 30, 2017 2100h UTC-4 where my Javascript is running.

Is there an easy way to get toLocaleString to treat the date instance according to its UTC equivalent?

Share Improve this question asked Mar 22, 2017 at 15:29 u936293u936293 16.2k34 gold badges121 silver badges219 bronze badges 2
  • Are you saying you'd like to be able to render the date as though your system were in GMT? – jessegavin Commented Mar 22, 2017 at 15:32
  • Yes, if I understand you correctly. – u936293 Commented Mar 22, 2017 at 15:32
Add a comment  | 

2 Answers 2

Reset to default 17

You can specify a parameter timeZone, which defines the target timezone to be used when formatting the date:

var date = new Date('2017-05-01T01:00:00.000Z');

console.log(date.toLocaleString("en-US", { month: "short", timeZone: 'America/New_York' }));
  // "Apr"

console.log(date.toLocaleString("en-US", { month: "short", timeZone: 'UTC' }));
  // "May"

// Adjust date to UTC 0
d = new Date(d.valueOf() + d.getTimezoneOffset() * 60000);
d.toLocaleString("en-US", { month: "short" })

UPDATE @Timo's answer is way better.

发布评论

评论列表(0)

  1. 暂无评论