The date/time libraries shipping with some languages I’ve used are just awful – e.g., Perl, Java, JavaScript. Fortunately, the first two have great libraries available DateTime for Perl and Joda-Time for Java.[1] For JavaScript, it’s slim pickings. There is DateJS which provides some parsing and fluent interface functionality, but seems to be lacking in other concepts (e.g., durations and intervals). But AFAICT there’s nothing of the comprehensiveness or extensibility of either of the Java or Perl alternatives.
While DateJS allows you to do math, there’s also a nice little hack you can do for at least one simple use case: given a date, what are the next and previous months?
In good APIs this is handled with ease:
In JavaScript you can’t do that. But you can find the previous/next months pretty easily. The Date constructor takes a series of values for defining the date. If you specify a day ‘0’ for the day of month, you’ll get the last day of the previous month, and if you specify a day ‘32’ you’ll get somewhere around the first day of the following month:
It’s not the same result, but that’s okay because the day is unnecessary. I’ve tested it in Rhino and a few browsers (FF, Chrome, IE 8) and all had the same result. Hope it helps.
[1] JDK 8 will vastly improve the default, taking it from terrible to awesome – see JSR 310.
[2] The ‘advance’ function is not in the core Ruby Date/DateTime library, but it is added by Rails. I had a devil of a time getting this to run as a standalone script so just ran it in the rails console. The interplay between the names of Ruby libraries, the classes, and the documentation is very confusing to an outsider – for example, ‘ri DateTime’ gives you methods monkeypatched into the class by ActiveSupport.