views:

59

answers:

1

I'm trying to convert a JSON date to a dd/mm/yyyy format, which I'm managing to do semi-successfully.

The problem I'm encountering is that the date from the record in the DB is for example, 2009-06-29 which is returning the usual JSON /Date(1246230000000)/, however, when I try and turn it into the previously mention dd/mm/yyyy format, it's coming through as today's date.

The code I'm using to try and do this is:

$('input#EmployeeName').result(function(event, data, formatted) {
    $('#StartDate').html(formatJSONDate(Date(!data ? '' : data.StartDate)));
});

function formatJSONDate(jsonDate) {
    var newDate = dateFormat(jsonDate, "dd/mm/yyyy");
    return newDate;
}

I'm using JavaScript Date Format to try and run the function.

Any help is greatly appreciated.

+2  A: 

Assuming your JSON looks something like this:

{
    "StartDate": "/Date(1224043200000)/"
}

you can convert it into an actual Javascript date like so:

var dt, millis;

millis = data.StartDate.match(/\/Date\((\d+)\)\//);
if (millis) {
    dt = new Date(Number(millis[1]));
}

That extracts the milliseconds since The Epoch value from the string and uses it to create a Date instance.

T.J. Crowder
And then you can `alert(dt.getDate()+'/'+(dt.getMonth()+1)+'/'+dt.getFullYear())`
Salman A