Skip to content

Instantly share code, notes, and snippets.

@spersico
Created January 31, 2022 15:10
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 spersico/49f2114b17ed2a7a50455a1db117b9b7 to your computer and use it in GitHub Desktop.
Save spersico/49f2114b17ed2a7a50455a1db117b9b7 to your computer and use it in GitHub Desktop.
tz-offset-calc - casidoo
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