Skip to content

Instantly share code, notes, and snippets.

@roobie
Last active August 28, 2015 07:29
Show Gist options
  • Select an option

  • Save roobie/103528cbd00e152c03f1 to your computer and use it in GitHub Desktop.

Select an option

Save roobie/103528cbd00e152c03f1 to your computer and use it in GitHub Desktop.
var tzWebOffsetPromise = function (timestamp) {
// returns a promise for the adjusted timezone for the supplied timestamp
return $.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/Web/RegionalSettings/TimeZone",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
}
}).then(function (tz) {
var isDST = function (date) {
// see http://stackoverflow.com/a/11888430
var stdTimezoneOffset = function (date) {
var jan = new Date(date.getFullYear(), 0, 1);
var jul = new Date(date.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
return date.getTimezoneOffset() < stdTimezoneOffset(date);
}
// description is a string like:
// "(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna"
// and we only want the actual offset:
var baseOffset = tz.d.Description.slice(4, 10).replace(':', '');
var val;
// check if the timestamp is in DST
if (isDST(new Date(timestamp))) {
// if it's currently DST, then we need to add an hour to the
// offset. So parse it, add an hour
// ['+0200' => 200 ] [DST]
val = (parseInt(baseOffset) + 100).toString();
// if val is less than 1000 then prepend a zero.
// and then build the corresponding tz offset string again.
// [ offset sign (+/-) ] [the value, padded to 4 digits]
return baseOffset.slice(0, 1) + ((val < 1000 ? '0' : '') + val);
}
return baseOffset;
});
}
var date = '2010-10-10T10:00:00.000';
tzWebOffsetPromise(date).then(function (offset) {
var adjustForTz = function (val) {
// IE and FF does not parse datetime strings with
// tz in them, so manually adjust:
var tz = offset;
var tzData = {
sign: tz.slice(0, 1) === '+' ? -1 : 1, // invert to adjust
hours: parseInt(tz.substr(1, 2), 10),
minutes: parseInt(tz.substr(3, 2), 10)
};
var dt = new Date(val + 'Z');
dt.setUTCHours(dt.getUTCHours() + tzData.sign * tzData.hours);
dt.setUTCMinutes(dt.getUTCMinutes() + tzData.sign * tzData.minutes);
return dt;
}
return adjustForTz(date);
});
@roobie
Copy link
Copy Markdown
Author

roobie commented Aug 27, 2015

tzWebOffsetPromise('10-10-2010 10:00').then(function (correctedOffset) {
  console.log(new Date(timestamp + correctedOffset));
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment