Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript setUTCHours returns wrong day

I've been playing around with the Date() object while studying when I noticed that setUTCHours() returns the wrong day.

Example:

var myDate = new Date(2014, 0, 1);
myDate.setUTCHours(10);
myDate;

Looking at this, I expected the date to be Wed Jan 01 2014 10:00:00 UTC, but instead Its one day behind. Why is that?

Here's my http://jsfiddle.net/L5QEC/ with comparisons to some other basic methods.

like image 380
Peter Silver Avatar asked Apr 24 '14 23:04

Peter Silver


2 Answers

Date objects use a time value that is UTC. They also have an offset that represents the timezone offset of the host system. By default, dates and times will use the offset to display local values. If you are UTC+1, then the offset will be -60 and new Date(2014, 0, 1) will create a date for 2013-12-31T23:00:00Z and use the offset to display a local date of 2014-01-01T00:00:00+0100.

So if you change the UTC hours to 10, the UTC time is: 2013-12-31T10:00:00Z and the local equivalent is 2013-12-31T11:00:00+0100.

So by setting the UTC hours to 10 you effectively set the local time to 11:00 (i.e. the UTC hours + 1 hour offset) on the previous day.

like image 146
RobG Avatar answered Oct 01 '22 17:10

RobG


If you'd like to set a specific date and time in UTC, consider:

var dt = new Date(Date.UTC(2014, 0, 1, 10, 0, 0));

The result will represent that point in universal time, but you will see it adjusted to the local time zone for display. For example:

"Wed Jan 01 2014 02:00:00 GMT-0800 (Pacific Standard Time)"
like image 38
Matt Johnson-Pint Avatar answered Oct 01 '22 15:10

Matt Johnson-Pint