Why does the month argument range from 0 to 11 in JavaScript's Date constructor?

后端 未结 8 1140
生来不讨喜
生来不讨喜 2020-11-22 15:31

When initializing a new Date object in JavaScript using the below call, I found out that the month argument counts starting from zero.

new Date(         


        
8条回答
  •  时光取名叫无心
    2020-11-22 16:12

    I know it's not really an answer to the original question, but I just wanted to show you my preferred solution to this problem, which I never seem to memorize as it pops up from time to time.

    The small function zerofill does the trick filling the zeroes where needed, and the month is just +1 added:

    function zerofill(i) {
        return (i < 10 ? '0' : '') + i;
    }
    
    function getDateString() {
        const date = new Date();
        const year = date.getFullYear();
        const month = zerofill(date.getMonth()+1);
        const day = zerofill(date.getDate());
        return year + '-' + month + '-' + day;
    }
    

    But yes, Date has a pretty unintuitive API, I was laughing when I read Brendan Eich's Twitter.

提交回复
热议问题