The difference is caused because new Date(2019, 2, 21)
creates the date in your current timezone. But when you do console.log(date)
it usually prints the date in UTC (different browsers have different behavior).
So when the dates new Date(2019, 2, 21)
and new Date()
were converted to UTC both were reduced by the same amount but new Date()
also gets the current time so the date didn't change.
console.log(new Date(2019, 2, 21));
console.log(new Date(2019, 2, 21).toString());
console.log(new Date(2019, 2, 21).toUTCString());
console.log(new Date());
console.log(new Date().toString());
console.log(new Date().toUTCString());
To create a date in UTC you should either add a Z
at the end when parsing from a string.
You can also get the Unix Time for a date by doing Date.UTC(year, month, date)
. You can create a date from that by doing new Date(Date.UTC(year, month, date))