JS Date methods

Someone wondered on Mastodon about the fact that .getMonth() returns a zero-based number while no other Date method does, but this turned out not to be a fact. Most other methods do return a zero-based number, and there's a simple logic to it.

The confusion really arises not from the fact that .getMonth() returns a zero-based number, but that .getDate() doesn't. It's natural to assume that .getDate() and .getMonth() will be analagous, but this is ultimately confusion between .getDate() and .getDay().

The thing is that dates are numbers, and these are pretty universally Hindu-Arabic numerals, whereas months and days have names that need to be rendered in multiple languages.

  • .getMonth() is really asking "which month of the year?," and returns 0–11 from January to December, which can be used to produce the correct month name for a given user's local language.
  • .getDay() is really asking, "which day of the week?," and returns 0–6 for Sunday through Saturday, again, allowing a programmer to use the day number to produce the correct name in a given language.

And the reason .getDate() doesn't return a zero-based number is clear if you think of the date as the name of the day, where it's an ordinal (i.e., 1 = first, 30 = thirtieth). The numeral representation is the near universal way of showing the ordinal name of the calendar date. And that's why it's not base zero.

Getting today's date, March 14, 2023, and using the .getDay() method, would return 2 (i.e., Tuesday, the third day in the base zero week from 0–6), while .getMonth() would return 2 (i.e., the third month in the base zero year from 0–11).

If I handle those returned values properly, everyone will see that it's the third of the month (3), but the number of the day of the week and the month of the year will be rendered for each of us according to our locale. I'll see "Tuesday" and "March," while a friend in France would instead see "Mardi" and "Mars."