Monday, March 16, 2015

Date column showing incorrect value for different timezone using javascript object model in SharePoint 2013

When you have multiple users in different zones, you will see the date value varies based on different timezone. The date which we are getting using javascript object model shows the local computer time and not the server time.

Suppose I have a list with column named "DateCompleted". I have added a new row with DateCompleted as 3/16/2015 12:00 AM.

When you use javascript client object model and display the date in web page. The result for teh below lines varies by differnt timezone.

var dateCompleted = oListItem.get_item('DateCompleted');

EST Timezone = > dateCompleted =  3/16/2015 12:00 AM.   (Server time)
PST Timezone = > dateCompleted =  3/15/2015 09:00 PM. 

To resolve the issue and display always the server time, you need to query the list again and use SP.Utilities.Utility.formatDateTime function. 

Below is the code you can refer to get the server time.

1:    var ctx = new SP.ClientContext(spotTargetSiteUrl);  
2:    var web = ctx.get_web();  
3:    var dateCompleted = oListItem.get_item('DateCompleted');  
4:    var dateStr = SP.Utilities.Utility.formatDateTime(ctx, web, dateCompleted, SP.Utilities.DateTimeFormat.dateOnly);  
5:    ctx.executeQueryAsync(  
6:       function (sender, data) {  
7:            // the below line will give you the server time  
8:           var serverDateCompleted = new Date(dateStr.m_value);  
9:       },  
10:       function (sender, args) {  
11:         ULSOnError(args.get_message(), document.location.href, 0);  
12:       }  
13:       );  

The line 8 above will give you the server time.

Hope this post will help you in resolving the date issue for different timezone.

Happy coding!!!!

No comments:

Post a Comment