Sunday, March 13, 2011

Handling Dates in Web Applications across MySQL, PHP and Javascript

A project on which I have been working recently requires dates and date spans to be read in via AJAX, displayed in the browser and saved to the database (also via AJAX). After feeling funny about the way I was handling the data, I realized that my application was plagued by the Year 2038 problem. It's like Y2K for Unix.

This came about because I like to create Javascript Date objects (on the client side) by using the MySQL unix_timestamp function to extract the timestamp (on the server side). Apparently, this will be useless on the server that I'm using in the year 2038. It must be 32-bit? Go me.

Currently, I'm getting around the issue by passing the month and year to the browser via AJAX instead of the timestamp.

Where before I had:
data['end_date'] = 1300074681
, I now have:
data['end_date_month'] = '03'
data['end_date_year'] = '2011'

I use Javscript's Date object's setMonth and setFullYear methods to setup the date:
endDate = new Date();
endDate.setMonth(data['end_date_month']);
endDate.setFullYear(data['end_date_year']);

Is there a better way to handle this? I haven't done much research on solutions to this problem yet.