I have come across some situations, when I am designing a HTML page for using as webresource in CRM and it primarily uses ODATA as communication protocol. One of the PITA scenario I have faces so far is handling dates with ODATA. ODATA is not an intelligent protocol as SOAP and I would say (not exactly true) that most of the data we get in ODATA will be a direct representation of the underlying DB table data.
This particular post presents a code snippet for converting a UTC time into time in current user's timezone using Javascript. The fundamental idea is to make use of CRM's internal time zone definition for time mapping.
I cannot take responsibility if there are any issues with CRM timezone definition though.
Jumping right into the code now.
GetLocalTimeFromUTC = function (dateObject) {
//dateObject should be a Universal Time. As the function name suggest, this function returns the time in current user's time zone assuming the dateObject is in UTC.
var yr = dateObject.getFullYear();
var userSetting = null;
function ErrorCallback(error) {
alert(error.message);
}
function userSettingSuccessCallback(result) {
userSetting = result;
}
var userId = Xrm.Page.context.getUserId();
//Modified SDK.REST.js to post synchronous requests. Hope you can do the same or mimic with XMLHttpRequest.
SDK.REST.retrieveRecord(userId, "UserSettings", "TimeZoneDaylightBias,TimeZoneDaylightDay,TimeZoneStandardMinute,TimeZoneCode,TimeZoneDaylightMinute,TimeZoneStandardDayOfWeek,TimeZoneStandardBias,TimeZoneDaylightSecond,TimeZoneStandardMonth,TimeZoneBias,TimeZoneDaylightHour,TimeZoneStandardDay,TimeZoneStandardHour,TimeZoneDaylightDayOfWeek,TimeZoneStandardSecond,TimeZoneStandardYear,TimeZoneDaylightMonth,TimeZoneDaylightYear", "", userSettingSuccessCallback, ErrorCallback);
if (userSetting != null) {
var dst_start = new Date(yr, userSetting.TimeZoneDaylightMonth - 1, (userSetting.TimeZoneDaylightDay * 7), userSetting.TimeZoneDaylightHour, userSetting.TimeZoneDaylightMinute, userSetting.TimeZoneDaylightSecond);
var dst_end = new Date(yr, userSetting.TimeZoneStandardMonth - 1, (userSetting.TimeZoneStandardDay * 7), userSetting.TimeZoneStandardHour, userSetting.TimeZoneStandardMinute, userSetting.TimeZoneStandardSecond);
// Calculcate the Daylight Savings start date for the year.
var day = dst_start.getDay();
dst_start.setDate((userSetting.TimeZoneDaylightDay * 7) - (day - userSetting.TimeZoneDaylightDayOfWeek));
// Calculcate the Daylight Savings end date for the year.
day = dst_end.getDay();
dst_end.setDate((userSetting.TimeZoneStandardDay * 7) - (day - userSetting.TimeZoneStandardDayOfWeek));
dateObject.setMinutes(dateObject.getMinutes() - (userSetting.TimeZoneBias));
if (dateObject >= dst_start && dateObject < dst_end) {
dateObject.setMinutes(dateObject.getMinutes() - (userSetting.TimeZoneDaylightBias));
}
}
return dateObject;
}