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.
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.
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)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With