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(
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.
They might've considered months to be an enumeration (first index being 0) and days not since they don't have a name associated with them.
Or rather, they thought the number of the day was the actual representation of the day (the same way months are represented as numbers in a date like 12/31), as if you could make a enumeration with numbers as the variables, but actually 0-based.
So actually, for the months, perhaps they thought the proper enumeration representation would be to use the month's name, instead of numbers, and they would've done the same if days had a name representation. Imagine if we'd say January Five, January Sixth, instead of January 5, January 6, etc., then perhaps they'd have made a 0-based enumeration for days too...
Perhaps subconsciously they thought about an enumeration for months as {January, February, ...} and for days as {One, Two, Three, ...}, except for days you access the day as a number rather than the name, like 1 for One, etc., so impossible to start at 0...