views:

161

answers:

3

What would be the best way to convert a mysql date format date into a javascript Date object?

mySQL date format is 'YYYY-MM-DD' (ISO Format).

+1  A: 

UNIX timestamp (milliseconds since the January 1, 1970) would be my preferred choice.

You can pass it around as an integer and use the JS setTime() method to make a JS Date object from it.

Ben S
A: 

You can split the date '-' as separator and use this constructor:

var d = new Date(Y, M - 1, D);
RC
and how would I split it like that?
Mike Valstar
if ds = 'YYYY-MM-DD': ds.split('-')
RC
+3  A: 

Given your clarification that you cannot change the format of the incoming date, you need something like this:

var dateParts = isoFormatDateString.split("-");
var jsDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);

Original response:

Is there a reason you can't get a timestamp instead of the date string? This would be done by something like:

 SELECT UNIX_TIMESTAMP(date) AS epoch_time FROM table;

Then get the epoch_time into JavaScript, and it's a simple matter of:

var myDate = new Date(epoch_time * 1000);

The multiplying by 1000 is because JavaScript takes milliseconds, and UNIX_TIMESTAMP gives seconds.

jhurshman
i have no access to change the way the data is returned to me. I have an ISO formatted date, I need to transform it clientside.
Mike Valstar