Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking toLocaleString() in UTC

Tags:

javascript

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?

like image 732
Old Geezer Avatar asked Dec 23 '22 19:12

Old Geezer


2 Answers

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"
like image 165
TimoStaudinger Avatar answered Dec 26 '22 08:12

TimoStaudinger


// 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.

like image 32
jessegavin Avatar answered Dec 26 '22 07:12

jessegavin