Skip to content

Instantly share code, notes, and snippets.

@JeremyRH
Last active March 25, 2024 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeremyRH/3fc818dc78caa8df7c7c45f43b19a9cf to your computer and use it in GitHub Desktop.
Save JeremyRH/3fc818dc78caa8df7c7c45f43b19a9cf to your computer and use it in GitHub Desktop.
dateToIsoWithTz.js
function dateToIsoWithTz(date, timeZone) {
// Use 'sv-SE' locale because it's similar to ISO.
const almostIsoFormatter = new Intl.DateTimeFormat('sv-SE', {
timeZone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short',
hour12: false
});
const [isoDate, isoTime, isoTzOffset] = almostIsoFormatter.format(date).split(' ');
// 'sv-SE' with timeZoneName: 'short' needs to be changed to ISO.
// Examples:
// GMT-7 => -07:00
// GMT-10 => -10:00
// GMT+5:30 => +05:30
const fullTzOffset = isoTzOffset.replace(/(UTC|GMT)(.?)(.*)/, (_, prefix, sign, shortTime) => {
// UTC or GMT with nothing after means no offset, i.e. ISO 'Z'.
if (!sign) {
return 'Z';
}
// Add leading and trailing zeros making sure to handle half-hour time zones.
const fullTzTime = shortTime.includes(':') ? shortTime.padStart(5, '0') : `${shortTime.padStart(2, '0')}:00`;
// 'sv-SE' uses char code 8722 for the minus sign instead of the usual char code 45.
return (sign === '+') ? `+${fullTzTime}` : `-${fullTzTime}`;
});
return [isoDate, isoTime, fullTzOffset];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment