Sudarshan's Blog

My Thoughts, Findings & Experiences

Convert JSON Date into JavaScript Date

August 14, 2011 07:39

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 Smile.

Happy programming!

Useful prototype functions for String and Array

October 4, 2010 06:32

Here is the listing of useful prototype functions for String and Array used in JavaScript:

String.format:
This function formats the string. This is equivalent of C# 'string.Format' function.

// This is similar to C# 'string.format' function
String.prototype.format = function() {
var txt = this,
i = arguments.length;

while (i--) {
txt = txt.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return txt;
};

// Usage:
'{0}:{1} {2} to {3}:{4} {5} {6}<br />'.format('07', '00', 'AM', '07', '00', 'PM');

// Output:
07:00 AM to 07:00 PM

String.replaceAll
This function removes matched string with the specified string.

// This is similar to 'string.Replace' function
String.prototype.replaceAll = function(pcFrom, pcTo) {
var i = this.indexOf(pcFrom);
var c = this;

while (i > -1) {
c = c.replace(pcFrom, pcTo);
i = c.indexOf(pcFrom);
}
return c;
}

// Usage:
'This is test. <BR> This is test.'.replaceAll("BR", "br");

// Output:
'This is test. <br> This is test.'

String.prototype.trim
This function trims spaces from left and right side of the string.

// Removes spaces from left and right side of string
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
}

// Usage:
' Testing functionality '.trim();

// Output:
'Testing functionality'

String.prototype.ltrim
This function trims spaces from left side of the string.

// Removes left side spaces from string
String.prototype.ltrim = function() {
return this.replace(/^\s+/, "");
}

// Usage:
' Testing functionality'.ltrim();

// Output:
'Testing functionality'

String.prototype.rtrim
This function trims spaces from right side of the string.

// Removes spaces from right side of the string
String.prototype.rtrim = function() {
return this.replace(/\s+$/, "");
}

// Usage:
'Testing functionality '.rtrim();

// Output:
'Testing functionality'

Array.contains
This function checks whether item exists in array or not.

// Attached "contains" method to array.
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}

return false;
}

// Usage:
var array = new Array(1, 2, 3, 4, 5);

1. array.contains(2);
2. array.contains(7);

// Output:
1. true
2. false

Array.prototype.remove
This function removes items from the array based on index.

// Attached "remove" method to array.
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;

return this.push.apply(this, rest);
};

// Usage:
var array = new Array(1, 2, 3, 4, 5);
array.remove(1,2);

// Output:
Array contents: 1,4,5

Array.prototype.getItem
This function gets the object from list of objects based on object id. Here assumed that 'Id' property contains object ID.

// Attached "getItem" method to array.
Array.prototype.getItem = function(id) {
var i = this.length;
while (i--) {
if (this[i]["Id"] === parseInt(id)) {
return this[i];
}
}
return null;
}

// Usage:
var entityList = new Array();
entityList.push({ Id: 1, Name: "Name 1" });
entityList.push({ Id: 2, Name: "Name 2" });

entityList.getItem(1);

// Output:
{ Id: 1, Name: "Name 1" }

Array.prototype.containsId
This function checks whether object with passed ID exists in the list of objects. Here assumed that 'Id' property contains object ID.

// Attached "containsId" method to array.
Array.prototype.containsId = function(id) {
var i = this.length;
while (i--) {
if (this[i]["Id"] === parseInt(id)) {
return true;
}
}
return false;
}

// Usage:
var entityList = new Array();
entityList.push({ Id: 1, Name: "Name 1" });
entityList.push({ Id: 2, Name: "Name 2" });

1. entityList.containsId(1);
2. entityList.containsId(7);

// Output:
1. true
2. false

Array.prototype.removeItem
This function removes the object from list of objects based on object id. Here assumed that 'Id' property contains object ID.

// Attached "removeItem" method to array.
Array.prototype.removeItem = function(id) {
var i = this.length;
while (i--) {
if (this[i]["Id"] === parseInt(id)) {
this.splice(i, 1);
return;
}
}
}

// Usage:
var entityList = new Array();
entityList.push({ Id: 1, Name: "Name 1" });
entityList.push({ Id: 2, Name: "Name 2" });
entityList.removeItem(1);

// Output:
'entityList' contents: { Id: 2, Name: "Name 2" }

Array.prototype.addItem
This function adds the object to list of objects.

// Attached "addItem" method to array.
Array.prototype.addItem = function(id) {
// Form an object if you want for passed 'id'
var obj = new obj();
this.push(obj);
}

OR

// Attached "addItem" method to array.
Array.prototype.addItem = function(obj) {
this.push(obj);
}

// Usage:
var entityList = new Array();
entityList.push({ Id: 1, Name: "Name 1" });
entityList.push({ Id: 2, Name: "Name 2" });

entityList.addItem({ Id: 3, Name: "Name 3" });

// Output:
'entityList' contents: { Id: 1, Name: "Name 1" }, { Id: 2, Name: "Name 2" }, { Id: 3, Name: "Name 3" }

Array.prototype.updateItem
This function updates the object property from list of objects based on object id. Here assumed that 'Id' property contains object ID.

// Attached "updateItem" method to array.
Array.prototype.updateItem = function(id, field, value) {
var i = this.length;
while (i--) {
if (this[i]["Id"] === parseInt(id)) {
this[i][field] = value;
}
}
}

// Usage:
var entityList = new Array();
entityList.push({ Id: 1, Name: "Name 1" });
entityList.push({ Id: 2, Name: "Name 2" });

entityList.updateItem(1, "Name", "Name 11");
alert(entityList[0].Name);

// Output:
Alert result: "Name 11";

All these items from listing are not written by me Smile (I just copied few of them by googling). Thanks to community who wrote some of them.

Happy programming!