-
-
Save spersico/49f2114b17ed2a7a50455a1db117b9b7 to your computer and use it in GitHub Desktop.
tz-offset-calc - casidoo
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
let humans = [ | |
{ name: 'Clara', timezone: 'UTC−4:00' }, | |
{ name: 'Cami', timezone: 'UTC−7:00' }, | |
{ name: 'Ximena', timezone: 'UTC−5:00' }, | |
]; | |
/** | |
* Return Hour & Minutes of a given human | |
* Optional 12/24hs format with a boolean | |
**/ | |
function localTime(personName, hour12 = true) { | |
if (typeof personName !== 'string') throw new Error('Invalid name'); | |
const person = humans.find((el) => el.name === personName); | |
if (!person) throw new Error('Person not found'); | |
const tz = person.timezone; | |
const tzOffset = Number( | |
tz.replace('UTC', '').replace(':', '.').replace('−', '-') | |
); | |
if (typeof tzOffset !== 'number') throw new Error('Invalid Timezone'); | |
const current = new Date(); | |
const localDiffToUTC = new Date().getTimezoneOffset() * 60000; | |
// Needed to account for the local tz of the browser running the function | |
const personDiffToUTC = tzOffset * 3600000; | |
const personDiffToLocal = localDiffToUTC + personDiffToUTC; | |
const personDate = new Date(current.getTime() + personDiffToLocal); | |
return personDate.toLocaleString('en-US', { | |
hour: 'numeric', | |
minute: 'numeric', | |
hour12, | |
}); | |
} | |
localTime('Clara'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment