SharePoint displays date/time according to TimeZone in Regional Settings but returns in UTC format in JSOM.
Using SP.TimeZone.Information
The folloiwing example demonstrates how to retrieve time zone offset using SP.TimeZone.Information
and then convert to SharePoint date/time using moment().zone()
:
var listTitle = 'Calendar';
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var item = list.getItemById(1);
context.load(item);
var timeZone = web.get_regionalSettings().get_timeZone();
context.load(timeZone);
context.executeQueryAsync(
function() {
var eventDate = item.get_item('EventDate');
var endDate = item.get_item('EndDate');
var timeZoneOffset = getTimeZoneOffset(timeZone); //exract TimeZone Offset
var localEventDate = moment(eventDate).zone(timeZoneOffset);
var localEndDate = moment(endDate).zone(timeZoneOffset);
console.log("Event Start date: " + localEventDate.format('YYYY-MM-DD hh:mm a'));
console.log("Event End date: " + localEndDate.format('YYYY-MM-DD hh:mm a'));
},
logError
);
function logError(sender,args)
{
console.log(args.get_message());
}
function getTimeZoneOffset(timeZone)
{
return timeZone.get_information().get_bias() + timeZone.get_information().get_daylightBias() + timeZone.get_information().get_standardBias();
}
Using SP.TimeZone.utcToLocalTime
SP.TimeZone.utcToLocalTime Method - converts the specified DateTime value from Coordinated Universal Time (UTC) to local time
The following example demonstrates how to use SP.TimeZone.utcToLocalTime
:
var listTitle = 'Calendar';
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var item = list.getItemById(1);
context.load(item);
var timeZone = web.get_regionalSettings().get_timeZone();
context.load(timeZone);
context.executeQueryAsync(
function onSucceeded() {
var eventDate = item.get_item('EventDate');
var endDate = item.get_item('EndDate');
var localEventDate = timeZone.utcToLocalTime(eventDate);
var localEndDate = timeZone.utcToLocalTime(endDate);
context.executeQueryAsync(
function() {
console.log(localEventDate.get_value());
console.log(localEndDate.get_value());
},
logError
);
},
logError
);
function logError(sender,args)
{
console.log(args.get_message());
}