Missing dateAdd, dateDiff

2005-11-03 23:16:00

Today one of my co-workers shared a post he found by Alex King on a Nasty PHP Oddity dealing with dates. The issue was caused by doing date incrementation using the simple expedient of adding or subtracting 86400 seconds to a Unix-style timestamp to move forward or back a day.

This works rather nicely for the most part, except for the day when Daylight Savings Time starts or ends, when a day is an hour longer or shorter.

Now I'll 'fess up here -- I actually got bitten in the ass by the exact same issue (only in JavaScript, not PHP) working on Scooby's week-to-week navigation code last week. Kind of felt like a doofus, actually -- a familiar feeling.

The predictable response on the OSAF dev mailing list was that the Chandler devs should all be using the Python 'timedelta' to increment or decrement dates. A good idea -- if your language gives you a nice, built-in, error-free way to avoid calculating a bunch of perilous date-related stuff manually, then using it is pretty obviously a Good Thing.

The problem here is that neither PHP nor JavaScript have native methods like Python 'timedelta' or (from my bad old days programming in ASP) DateDiff or DateAdd in VBScript for smoothing out the weird complexities of dealing with dates.

After a bit of Googling, I did find something for JavaScript called jsDate which looks fairly promising, and seems to be very well maintained. The only issue I can see with it is that the author doesn't clearly state what license the code is available under -- he just says "Use freely, but be honest about it. I just ask for credit."

I've gone ahead and implemented a JavaScript strftime. Sure would be nice to have a dateAdd too.


This is the blog for Matthew Eernisse. I currently work at Yammer as a developer, working mostly with JavaScript. All opinions expressed here are my own, not my employer's.


Previous posts

All previous posts ยป

This blog is a GeddyJS application.