Zero-based date, Christmas, and emoji

1 min read
1710 views

Here’s a quick tip if you’re starting out with JavaScript: which of the following values passed to the getMonth() and getDate() methods will print December 25?

11,24
11,25
12,25

If you answered 11,25, have some egg nog and an extra piece of ribbon candy, you’re doing awesome.

Zero-based counting

JavaScript counters start at 0. But it’s important to know that not every method in the Date object returns a zero-based number. Specifically, getMonth() counts from 0, whereas getDate() counts from 1.

Months can also be represented as a string name, so using zero-based counting for getMonth() makes it possible to index months into an array, e.g.:

let months = ['Jan', 'Feb', 'Mar', 'Apr'...];
months[new Date().getMonth()];

But if you’re starting to wonder, “Why does this method count from 0, and this method count from 1?”, the answer is a matter of practicality: it’s because the Date class in Java does it this way.

So there’s a bit of nuance with counting using some of the JavaScript Date methods. And we know that 11,25 will print December 25.

Okay, is it Christmas yet?

See the Pen Is It Christmas? by Matt Smith (@AllThingsSmitty) on CodePen.