Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript date - preserve timezone offset

I have a ISO8601 date that contains a timezone offset (see below). When I create a Date object from this, the date object is converted into my timezone (currently GMT), and timezone offset goes to 0. Is there any way to get the Date() constructor to preserve the timezone offset?

  var date = new Date("2012-01-17T12:55:00.000+01:00");
  console.log(date.toString());

The output I get is:

"Tue Jan 17 2012 11:55:00 GMT+0000 (GMT)"

The output I want is:

"Tue Jan 17 2012 12:55:00"
like image 677
Kevin Avatar asked Jan 16 '12 16:01

Kevin


1 Answers

Not with the built-in Date object, as they're only aware of Local (as defined by the user's browser and/or OS settings) and UTC. You can see this from the many cloned methods the class has (e.g., getHours / getUTCHours).

getTimezoneOffset is the only timezone info you really have, but it's local as well and will probably only give you +0 again (or +6 in my case):

var date = new Date("2012-01-17T12:55:00.000+01:00");
console.log(date.getTimezoneOffset() / 60.0);

You can try timezone-js (or one of its forks), but you'll need to know the Olson timezone name not just the GMT/UTC offset:

var date = new new timezoneJS.Date('2012-01-17T12:55:00.000+01:00', 'Europe/Brussels');
alert(date.getTimezoneOffset() / 60.0); // +1
like image 64
Jonathan Lonowski Avatar answered Sep 22 '22 10:09

Jonathan Lonowski