JSON date string to Date Object using RegEx

JSON has become de-facto standard for web services. When you use JSON in web services the date is returned as some numbers. How to convert it to readable date format? Checkout the following code on how we utilise Regular Expression to tackle this..

var prettyDate = prettyDate("/Date(1277334000000+0100)/");
alert(prettyDate);

var prettyTime = prettyTime("/Date(1277334000000+0100)/");
alert(prettyTime );

function prettyDate(servDate){	
	if (servDate == null){
		return "";
	}
	else{
		var dateStr = servDate.replace(///g,"");
		var d = eval("new "+dateStr);
		var retStr = d.getFullYear()  "-" + pad2((d.getMonth()+1)) + "-" + pad2(d.getDate());
		return retStr;
	}
	
}

function prettyTime(servDate){	
	if (servDate == null){
		return "";
	}
	else{
		var dateStr = servDate.replace(///g,"");
		var d = eval("new "+dateStr);
		var retStr = pad2(d.getHours()) + ":" + pad2(d.getMinutes());
		return retStr;
	}
	
}


function pad2(number) {   
	return (number < 10 ? '0' : '') + number;  
}
Did you enjoy this article?
Signup today and receive free updates straight in your inbox. We will never share or sell your email address.

Leave a Reply