Last active
March 25, 2024 19:29
-
-
Save JeremyRH/3fc818dc78caa8df7c7c45f43b19a9cf to your computer and use it in GitHub Desktop.
dateToIsoWithTz.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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