Bhumi Singhal Bhumi Singhal - 1 year ago 83
Javascript Question

new Date(2015,2,30) and new Date('2015-2-30')

Both the above new date formats give different results.

new Date(2015,2,30) : Date 2015-03-29T18:30:00.000Z

new Date('2015-2-30') : Invalid Date

Why is this different ?

Points :
1. Month index in the first format start with 0.
2. The first format handles the overflow of the dates and hence is not a prefered way to test for invalid dates.

For eg :
new Date(2015, 1, 30) {when the user is looking for 30,Feb,2015}
will be converted to 01,March,2015. That is the extra date is carry forwarded to the month. Pretty indecent a convert according to me. However, if you write
new Date("2015-2-30"){when the user is looking for 30,Feb,2015}
, this will be an invalid date.

Answer Source

You should do like the following

console.log(new Date(2015,2,30)); // here 2 represents the march, ,month starts from 0 where 0 represents first month
console.log(new Date('2015-3-30'));

Mon Mar 30 2015 00:00:00 GMT+0530 (India Standard Time)
Mon Mar 30 2015 00:00:00 GMT+0530 (India Standard Time)

new Date('2015-2-30') // it means 30th day in February; which will convert it to second march 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download