Skip to content

Instantly share code, notes, and snippets.

@andrewchilds
Created May 3, 2022 18:37
Show Gist options
  • Save andrewchilds/329f0cbdd23bc33d7e194362a71fe1c4 to your computer and use it in GitHub Desktop.
Save andrewchilds/329f0cbdd23bc33d7e194362a71fe1c4 to your computer and use it in GitHub Desktop.
Convert a minute-based timezone offset like `240` to an offset like `"-04:00"`.
// Converts a getTimezoneOffset() offset to one that can be used in new Date().
// Examples:
// Eastern Standard Time: 240 -> '-04:00'
// India Standard Time: -330 -> '+05:30'
// Australian Central Western Standard Time: -525 -> '+08:45'
export function getTimezoneOffset(d) {
return convertTimezoneOffset(d.getTimezoneOffset());
}
export function convertTimezoneOffset(offset) {
const plusMinus = offset > 0 ? '-' : '+';
const hours = Math.abs(Math.ceil(offset / 60)) + '';
const minutes = (Math.abs(offset) % 60) + '';
return `${plusMinus}${hours.padStart(2, '0')}:${minutes.padStart(2, '0')}`;
}
@andrewchilds
Copy link
Author

Usage examples:

convertTimezoneOffset(0);
'+00:00'
convertTimezoneOffset(240);
'-04:00'
convertTimezoneOffset(-330);
'+05:30'
convertTimezoneOffset(-525);
'+08:45'

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