I got tired of dealing with this issue, and I didn’t want to use any third party libraries so I wrote a quick little helper class to help you deal with this date formatting issue.
This “formatJSONDateLocal” method will convert from UTC Time to the clients local time. This is very handy when working with services storing time as UTC. If I improve it I will update this post.
You can modify the formatJSONDateLocal to get the format you are looking for.
The CLASS:
var ViviScapeWCFDateHelper = {
formatJSONDate: function (jsondate) {
var sdate = new Date(parseInt(jsondate.substr(6)));
var formattedsdate = sdate.getFullYear() + "-" + ("0" + (sdate.getMonth() + 1)).slice(-2) + "-" + ("0" + sdate.getDate()).slice(-2);
return formattedsdate;
},
formatJSONDateLocal: function (jsondate) {
var odate = new Date(parseInt(jsondate.substr(6)));
var today= new Date();
var offset = today.getTime() + (today.getTimezoneOffset() * 60000);
var sdate = new Date(odate + (3600000 * offset));
var realhour = (sdate.getHours() > 12) ? sdate.getHours() - 12 : sdate.getHours();
var ampm = (sdate.getHours() >= 12) ? "PM" : "AM";
var formattedsdate = sdate.getFullYear() + "-" + ("0" + (sdate.getMonth() + 1)).slice(-2) + "-" + ("0" + sdate.getDate()).slice(-2) + " " + realhour + ":" + sdate.getMinutes() + ampm;
return formattedsdate;
}
}
This is how you use it:
//Convert WCF JSON DATE to Date
ViviScapeWCFDateHelper.formatJSONDate(wcfjsondate);
//Convert WCF JSON UTC DateTime to local datetime
ViviScapeWCFDateHelper.formatJSONDateLocal(wcfjsondate);