JavaScript Date
I recently used the Date builtin to implement some date/time manipulation in JavaScript. Some parts of it were quite surprising. I think API design is an important part of programming, so I decided to share this with you. Maybe you can learn something from it.
Note that a more modern date/time library is in the process of being standardized, so please see this as critique of a hopefully soon to be obsolete part of JS.
The Name
It's called Date
, but it also represents time.
getYear()
Guess what this returns:
new Date().getYear()
You guessed correctly, it's 120
(as of 2020)! It's defined as the year of the
given date minus 1900 (read: a two digit year for everything between 1900 and
2000. Formatting years that way was popular some time ago).
If you want to get the year without any offset you have to use getFullYear()
.
getMonth()
What is wrong in this piece of date formatting code?
const d = new Date();
return d.getMonth() + '/' + d.getDate() + '/' + d.getFullYear();
Obviously the order of month and date if you are from Europe, but that's beside the point. ;)
The getMonth()
method returns a number between 0 and 11 (let that sink in). My
guess is that it was designed that way to make translating the return value to
a month name easier:
return [
'Jan',
'Feb',
...
][d.getMonth()];
Odd choice.
getDate()
It returns the day of the month and it's 1-based of course. Contrary to
getMonth()
, which is 0-based.
getDay()
I first thought this will return the day of the month, but it returns the
weekday instead. Maybe getWeekDay()
would have been a better name.
Is There More?
I'm sure there are more gems in there, but those were the ones that I stumbled
upon. What is your favorite pitfall in Date
?