WCF Javascript Date Helper Class


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

Advertisements

About Art Hicks

I am Business Owner/Applications Engineer that specializes in providing rich solutions to my clients and colleagues.
This entry was posted in .NET WCF Services, HTML5, Integration, JavaScript, jQuery. Bookmark the permalink.

Leave a Reply

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s