JSON is becoming very popular format to exchange data between client and server in Web 2.0 applications. Everything works very smooth apart from date in JSON. Date format in JSON is something like ‘\/Date(-606769200000-0500)\/’ where ‘-606769200000’ is number of milliseconds from January 1, 1970 and ‘-0500’ is time offset.
Now, to convert this JSON date into normal JavaScript date is nightmare. There are lot of solutions available, but none of them works perfectly.
So, finally, we come up with solution which will parse JSON date correctly considering time zone information as well.
Solution 1: (without using regular expression)
function parseJsonDate(jsonDate) {
// Get the date time part
var dateTimePart = jsonDate.replace(/\/+Date\(([\d+-]+)\)\/+/, '$1');
// Check for + or - sign
var minusSignIndex = dateTimePart.indexOf('-');
var plusSignIndex = dateTimePart.indexOf('+');
// Get the sign index
var signIndex = minusSignIndex > 0 ? minusSignIndex : plusSignIndex;
// If sign index is not 0 then we are extracting offset part and
if(signIndex > 0) {
var datePart = dateTimePart.substring(0, signIndex);
var offsetPart = dateTimePart.substring(signIndex);
var offset = offsetPart.substring(0,3) + '.' + ((parseFloat(offsetPart.substring(3)) / 60) * 100).toString();
return getJSDate(parseFloat(datePart), parseFloat(offset));
}
else {
return getJSDate(dateTimePart, 0);
}
}
function getJSDate(ms, offset) {
// create Date object for current location
var date = new Date(ms);
// convert to msec
// add local time zone offset
// get UTC time in msec
var utcTime = date.getTime() + (date.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var jsDate = new Date(utcTime + (3600000*offset));
return jsDate;
}
Solution 2: (with the power of regular expression – Thanks to Jon)
function parseJsonDate(jsonDate) {
var offset = new Date().getTimezoneOffset() * 60000;
var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);
if (parts[2] == undefined)
parts[2] = 0;
if (parts[3] == undefined)
parts[3] = 0;
return new Date(+parts[1] + offset + parts[2]*3600000 + parts[3]*60000);
};
Now, no need of ugly solutions like passing date in string format .
Happy programming!