Get Timezone from a date

Asked

Viewed 79 times

2

I have that date:

2016-02-22T14:55:00.000-03:00

And I’d like to take the Timezone:

-03:00

Automatically, without having to perform any regex.

1 answer

4


If this date is returning as a string, you can use replace

var str = "2016-02-22T14:55:00.000-03:00";
var timezone = str.substr(str.length - 6);
console.log(timezone);

If the date is in timestamp format, you can do as follows:

var offset = new Date("2016-02-22T14:55:00.000-03:00").getTimezoneOffset();

var o = Math.abs(offset);

var timezone = (offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2) + ":" + ("00" + (o % 60)).slice(-2);

console.log(timezone);

The method getTimezoneOffset returns the difference in minutes from UTC to local date/time. Then it checks the value in minutes and converts to hours ( divine the value by 60 ) and formats the value legibly as time and operator (+/-).

Soen font¹

  • Good, but if it’s timestamp format ?

  • Added alternative, @Jonathan

Browser other questions tagged

You are not signed in. Login or sign up in order to post.