Skip to content

Instantly share code, notes, and snippets.

@alloy-d
Created September 19, 2012 17:38
Show Gist options
  • Save alloy-d/3751008 to your computer and use it in GitHub Desktop.
Save alloy-d/3751008 to your computer and use it in GitHub Desktop.
Given a JS date object, get an ISO 8601 string for the beginning of that day in a target timezone.
var beginningOfDayWithOffset = function (targetOffset) {
var pad = function (n) { return (n.toString().length === 2 ? n.toString() : "0" + n) }
var sign = "-";
var offsetHours, offsetMinutes, offsetString;
// That's right, JavaScript's timezone offset has the opposite sign of the
// offset in ISO 8601...
if (targetOffset <= 0) {
sign = "+";
targetOffset = -targetOffset;
}
offsetHours = parseInt(targetOffset / 60);
offsetMinutes = targetOffset % 60;
offsetString = sign + pad(offsetHours) + pad(offsetMinutes);
return function (date) {
var localOffset = date.getTimezoneOffset();
var offsetFromTarget = targetOffset - localOffset;
var bod = new Date(date);
// This will have the effect of adding or subtracting hours to make the
// "local" time match the local time in the target time zone, crossing day
// boundaries if necessary.
bod.setMinutes(bod.getMinutes() + offsetFromTarget);
return bod.getFullYear() + "-" +
pad(bod.getMonth() + 1) + "-" +
pad(bod.getDate()) + "T00:00:00" +
offsetString;
}
}
// For example, EST (UTC-5):
var beginningOfDayEST = beginningOfDayWithOffset(300);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment