Search code examples
javascriptdateunix-timestamp

Javascript's Date object weird behaviour


I'm trying to create a Date() object from a date formatted dd/mm/yyyy and sometimes it works and sometimes it's doesn't. For example:

new Date('12/05/2008 00:00:00'); //OK
new Date('13/05/2008 00:00:00'); //Invalid Date????

I happens again in a few specific dates. Am I missing something?

Another thins is when I try to get the js timestamp of created date it acts weird too.

(new Date('12/05/2008 00:00:00')).getTime() //Returns 1228428000000
(new Date('01/06/2008 00:00:00')).getTime() //Returns 1199570400000

So somehow more time as passed between 1/1/1970 to 12/05/2008 than 1/1/1970 to 01/06/2008?


Solution

  • The Date constructor expects strings of that format to follow the North American convention for writing dates (mm/dd/yyyy) rather than the one used by most other countries (dd/mm/yyyy) so you need to convert between them:

    var date = '22/05/13'; // today's date according to me (I'm British)
    
    date = date.split('/');
    date = date[1]+'/'+date[0]+'/'+date[2];
    
    console.log(new Date(date).toString());
    

    However, to avoid ambiguity you might want to use another way of entering the date:

    var year = 2013, 
        month = 4, // note that months are 0-based when using this approach (i.e. Jan = 0) 
        day = 22;
    new Date(year, month, day);