Sample code to parse JSON Date Format

Hi,

Just sharing a sample code to parse JSON Date Format (e.g. “\/Date(628318530718)\/”) to Date.


entity = JSON.parse(retrieveReq.responseText).d;

if (entity['BirthDate'] != null) {

var jdate = parseJsonDate(entity['BirthDate']);
 var year = jdate.getFullYear();
 var month = jdate.getMonth() + 1 < 10 ? '0' + (jdate.getMonth() + 1) : (jdate.getMonth() + 1);
 var date = jdate.getDate() < 10 ? '0' + jdate.getDate() : jdate.getDate();
 var dateString = month + '/' + date + '/' + year;

 alert(dateString);
 }

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);
 }

}

Bye.


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s