Skip to content

Instantly share code, notes, and snippets.

@emersonbroga
Created February 14, 2019 00:09
Show Gist options
  • Save emersonbroga/b908094550aa8913d87fe71e31ed2346 to your computer and use it in GitHub Desktop.
Save emersonbroga/b908094550aa8913d87fe71e31ed2346 to your computer and use it in GitHub Desktop.
Front-end Javascript: Get a specific date/time from a defined Timezone.

#Front-end Timezone with javascript

Dependencies:

date-fns date-fns-timezone

##How to Run:

npm install
node index.js
const dateFNS = require('date-fns');
const dateFNSTimezone = require('date-fns-timezone');
const { isWithinRange: isBetween } = dateFNS;
const { formatToTimeZone } = dateFNSTimezone;
const isDate = (date) => {
return (date instanceof Date);
}
const parseToTwoDigitString = (digits) => ('0' + digits).substr(-2);
const parseTime = (time) => {
if (!time || typeof time !== 'string' || time.indexOf(':') === -1) return 0;
const [h,m,s] = time.split(':');
const hours = h ? parseInt(h) : 0;
const minutes = m ? (parseInt(m) * 60) : 0;
const seconds = s ? parseInt(s) : 0;
return {hours, minutes, seconds};
}
const parseTimeToSeconds = (time) => {
const { hours, minutes, seconds } = parseTime(time);
return (hours * 60 * 60) + (minutes * 60) + seconds;
}
function setTime(date, time, offset) {
const selectedOffset = offset || '000';
const year = date.getFullYear();
const month = parseToTwoDigitString(date.getMonth() + 1);
const day = parseToTwoDigitString(date.getDate());
const { hours, minutes, seconds } = parseTime(time);
const h = parseToTwoDigitString(hours);
const m = parseToTwoDigitString(minutes);
const s = parseToTwoDigitString(seconds);
const dateString = `${year}-${month}-${day}T${h}:${m}:${s}Z`;
const result = new Date(dateString);
return result;
}
const parseTimeToHours = (time) => parseTimeToSeconds(time) / 60 / 60;
const parseDateToUTC = (date) => {
const utc = Date.UTC(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds()
);
return new Date(utc);
}
const setTimeForDateAtATimezone = (date, time, timezone) => {
if (!isDate(date)) throw new Error('setTimeForDateAtATimezone date is not a valid date.');
const timeInHours = parseTimeToHours(time);
const timezoneOffset = formatToTimeZone(date, 'Z', { timeZone: timezone });
const offsetInHours = parseTimeToHours(timezoneOffset);
const newDate = setTime(date, time);
return new Date(newDate.setHours(newDate.getHours() + (offsetInHours * -1)));
}
function setTimezone(date, timezone) {
return new Date(formatToTimeZone(date, 'YYYY-MM-DDTHH:mm:ssZ', { timeZone: timezone }));
}
// if you're in LA, try a different TZ.
const TZ = 'America/Los_Angeles';
const now = new Date();
const currentLATime = setTimezone(now, TZ);
const locationAt9am = setTimeForDateAtATimezone(now, '09:00', TZ);
const locationAt5pm = setTimeForDateAtATimezone(now, '17:00', TZ);
const isOpen = isBetween(currentLATime, locationAt9am, locationAt5pm);
console.log('currentLATime:.....', currentLATime.toISOString(), ' in UTC');
console.log('LocationAt9am:.....', locationAt9am.toISOString(), ' in UTC');
console.log('locationAt5pm:.....', locationAt5pm.toISOString(), ' in UTC');
console.log('isOpen:............', isOpen ? 'YES' : 'NO');
{
"name": "Front-end date time from a specific timezone.",
"version": "1.0.0",
"description": "Get a datetime for a specific timezone using front-end javascript",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Emerson Carvalho",
"license": "ISC",
"dependencies": {
"date-fns": "^1.30.1",
"date-fns-timezone": "^0.1.4",
},
"devDependencies": {
"@types/date-fns": "^2.6.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment