javascript

JavaScript Date set not working as expected


My code returning

Sat Jan 25 2020 15:06:45 GMT+0530 (India Standard Time)

Anyone, please tell me why it is not working as per my expectations?

Code:

let date1 = new Date(2019, 12, 25);
console.log(date1);


Solution

  • In JavaScript, the month of a Date is similar to an index of an array, in the aspect that it starts from 0 and goes to 12.

    So you should do:

    let date1 = new Date(2019, 11, 25);
    console.log(date1);

    Keep in mind that console.log(date) will return the date in UTC format so it might be off by a few hours (which might also change the date by 1), do console.log(date.toString()) instead.