简体   繁体   中英

Why are my dates aren't working in TypeScript?

I'm trying to initialize a Date object by doing:

let date = new Date(2020, 12, 5, 0, 0, 0, 0);

then when I do

date.getMonth()

I get 0 .

Can someone help me?

Months are zero-indexed, so the month you want to initialize it with is actually 11. It doesn't know what to do with 12, that would be month number 13.

date.getMonth() returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year) according to the docs .

The month argument of Date is zero based - 0 represents January and 11 represents December. Assuming you meant to create an object for the fifth of December 2020, you should use 11, not 12:

let date = new Date(2020, 11, 5, 0, 0, 0, 0);
// Here ------------------^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM