How do I specify the time zone when creating a JavaScript Date?

Can someone explain how Date.UTC works

Date.UTC creates a timevalue for the provided year, month, date, etc. without any offset. So if the client machine is set for, say, UTC +05:00 then:

var d = new Date(Date.UTC(2013, 11, 30, 12, 0, 0));

will create a date equivalent to noon on 30 December 2013 at Greenwich. Alerting the date will print a local time (assuming +5:00) equivalent to 2013-12-30T17:00:00+05:00.

and how do I set a timezone so my countdown clock is counting down based on the specified timezone?

You can’t set the timezone, however you can use UTC values to create a date object, adjust the hours and minutes for the offset, then use the UTC methods to get the date and time components for the countdown.

e.g.

function z(n){return (n < 10? '0' : '') + n;}

var d = new Date(Date.UTC(2012, 11, 30, 12, 0, 0));

d.setUTCHours(d.getUTCHours() - 7);

alert(d.getUTCFullYear() + '-' + z(d.getUTCMonth() + 1) + '-' + 
      z(d.getUTCDate()) + 'T' + z(d.getUTCHours()) + ':' +
      z(d.getUTCMinutes()) + ':' + z(d.getUTCSeconds()) + '-07:00'
);

// 2012-12-30T05:00:00-07:00

If non–UTC methods are used, the local offset will affect the result.

Leave a Comment