Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date.UTC() function is off by a month?

I was playing around with Javascript creating a simple countdown clock when I came across this strange behavior:

var a = new Date(),  now = a.getTime(), then = Date.UTC(2009,10,31), diff = then - now, daysleft = parseInt(diff/(24*60*60*1000)); console.log(daysleft ); 

The days left is off by 30 days.

What is wrong with this code?

Edit: I changed the variable names to make it more clear.

like image 217
picardo Avatar asked Oct 02 '09 03:10

picardo


People also ask

Does JavaScript date use UTC?

The Date. UTC() method in JavaScript is used to return the number of milliseconds in a Date object since January 1, 1970, 00:00:00, universal time. The UTC() method differs from the Date constructor in two ways: Date.

Is new date () getTime () UTC?

Use the getTime() method to get a UTC timestamp, e.g. new Date(). getTime() . The method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation. Calling the method from any time zone returns the same UTC timestamp.

How do you set a date to UTC?

The Javascript date can be converted to UTC by using functions present in Javascript Date object. The toUTCString() method is used to convert a Date object into a string, according to universal time. The toGMTString() returns a string which represents the Date based on the GMT (UT) time zone.


2 Answers

The month is zero-based for JavaScript.

Days and years are one-based.

Go figure.

UPDATE

The reason this is so, from the creator of JavaScript, is

JS had to "look like Java" only less so, be Java's dumb kid brother or boy-hostage sidekick. Plus, I had to be done in ten days or something worse than JS would have happened.

http://www.jwz.org/blog/2010/10/every-day-i-learn-something-new-and-stupid/#comment-1021

like image 167
Eric J. Avatar answered Oct 03 '22 18:10

Eric J.


As Eric said, this is due to months being listed as 0-11 range.

This is a common behavior - same is true of Perl results from localtime(), and probably many other languages.

This is likely originally inherited from Unix's localtime() call. (do "man localtime")

The reason is that days/years are their own integers, while months (as a #) are indexes of an array, which in most languages - especially C where the underlying call is implemented on Unix - starts with 0.

like image 26
DVK Avatar answered Oct 03 '22 17:10

DVK