Crap that annoys me, part 20184: Javascript dates
2010-04-09 2:13 pm ∴ Crap that Annoys Me ∴ by matt -

I realize that a lot of my posts are rants, especially when I’m dealing with PHP, and I hate sounding like a jerk/whiner/maniac…

But I just couldn’t help myself today.

Today’s gripe is about Javascript and Dates. There is a convenient Date object that handles just about everything I, as a web programmer, need when handling Dates in Javascript. However, there’s one particular thing that I think is probably the dumbest thing I’ve ever seen.

//So let's say we have to get some information about today's date.
//It's April 9th.
//I want the number of the month and the day in this format: m/d
var now = new Date();
document.write(now.getMonth() + "/" + now.getDate())
//What do I get?
//  3/9

There are three things wrong.

  1. Getters and Setters — die, ok? Strings and Arrays have a length property, it’s not blah.getLength(). Date objects have no properties (that I’m aware of).
  2. Keeping in mind that I must use a method begrudgingly, it should be getDay() instead of getDate(). To me, getDate() implies that you’re getting a full date string, or a Date Object, which you already have, which wouldn’t make sense. getDay() returns the day of the week, which should be getDayOfWeek().
  3. You probably noticed that the value of getMonth() is wrong. Technically, it isn’t. getMonth() returns the zero-based month number, you know, just like how they count months in nowhere on Planet Earth! Who the hell thought up this? I know that I might want to use an array of month names because the Date Object doesn’t really provide a way to get that, but most of the time, no.

    Why then, aren’t the calendar days zero based? I don’t get it.

    This could be inspired from POSIX C, in which the tm structure has many of the same details — although not as getters and setters — and specifies that months are, you guessed it, numbered 0 to 11.

    It also gives room for up to 2 leap seconds in the structure, which is really useful. No really, if you’re using localtime_r() for high-precision timing, or polling every second of every day to see if there might be a leap second…I’ll punch you.