UNPKG

timezone-js-ts

Version:

288 lines (287 loc) 12.3 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.getDestinationTime = getDestinationTime; exports.timezoneConverter = timezoneConverter; exports.allTimezones = allTimezones; exports.timezonesByPlace = timezonesByPlace; exports.getAllCities = getAllCities; exports.getAllStates = getAllStates; exports.getAllCountries = getAllCountries; const allZoneData = __importStar(require("./all_timezone_lists.json")); const citiesData = __importStar(require("./cities.json")); const statesData = __importStar(require("./states.json")); const countriesData = __importStar(require("./countries.json")); const zoneData = __importStar(require("./countries-with-timezone.json")); // import * as fs from 'fs'; // import * as path from 'path'; // --------------------------------------------------------- // ------------------------- Helpers ---------------------- // --------------------------------------------------------- const monthArr = [ { name: 'January', value: 1 }, { name: 'Feburary', value: 2 }, { name: 'March', value: 3 }, { name: 'April', value: 4 }, { name: 'May', value: 5 }, { name: 'June', value: 6 }, { name: 'July', value: 7 }, { name: 'Augest', value: 8 }, { name: 'September', value: 9 }, { name: 'October', value: 10 }, { name: 'November', value: 11 }, { name: 'December', value: 12 }, ]; const sourceTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; function timeNowIs(timezone, timestyle) { timestyle = timestyle ? timestyle : 'full'; const date = new Date(); const configOptions = { timeZone: timezone, dateStyle: 'full', timeStyle: timestyle }; return new Intl.DateTimeFormat('en-GB', configOptions).formatToParts(date); } function getTimezoneName(data, timestyle) { timestyle = timestyle ? timestyle : 'full'; const dateObj = timeNowIs(data, timestyle); const findTz = dateObj.find(z => z.type === 'timeZoneName'); var tzStr = findTz.value; return tzStr; } function getTimeDiff(IANA_timezone_destination, IANA_timezone_source) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; IANA_timezone_source = IANA_timezone_source ? IANA_timezone_source : sourceTimeZone; let timeDiff; // const currTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; const destTime = timeNowIs(IANA_timezone_destination); let destHour = (_a = destTime.find(h => h.type == 'hour')) === null || _a === void 0 ? void 0 : _a.value; let destMinute = (_b = destTime.find(h => h.type == 'minute')) === null || _b === void 0 ? void 0 : _b.value; const destSecond = (_c = destTime.find(h => h.type == 'second')) === null || _c === void 0 ? void 0 : _c.value; const destDay = (_d = destTime.find(h => h.type == 'day')) === null || _d === void 0 ? void 0 : _d.value; let destMonth = (_e = destTime.find(h => h.type == 'month')) === null || _e === void 0 ? void 0 : _e.value; const destYear = (_f = destTime.find(h => h.type == 'year')) === null || _f === void 0 ? void 0 : _f.value; const currTime = timeNowIs(IANA_timezone_source); let currHour = (_g = currTime.find(h => h.type == 'hour')) === null || _g === void 0 ? void 0 : _g.value; let currMinute = (_h = currTime.find(h => h.type == 'minute')) === null || _h === void 0 ? void 0 : _h.value; const currSecond = (_j = currTime.find(h => h.type == 'second')) === null || _j === void 0 ? void 0 : _j.value; const currDay = (_k = currTime.find(h => h.type == 'day')) === null || _k === void 0 ? void 0 : _k.value; let currMonth = (_l = currTime.find(h => h.type == 'month')) === null || _l === void 0 ? void 0 : _l.value; const currYear = (_m = currTime.find(h => h.type == 'year')) === null || _m === void 0 ? void 0 : _m.value; currMonth = monthArr.find((m) => m.name == currMonth).value; destMonth = monthArr.find((m) => m.name == destMonth).value; const currDateTimeSmplFrmt = `${currDay}-${currMonth}-${currYear} ${currHour}:${currMinute}:${currSecond}`; const destDateTimeSmplFrmt = `${destDay}-${destMonth}-${destYear} ${destHour}:${destMinute}:${destSecond}`; if (currDateTimeSmplFrmt > destDateTimeSmplFrmt) { let minute = currMinute - destMinute; if (currHour == '00') { currHour = 24; } if (currMinute < destMinute) { minute = destMinute - currMinute; currHour = currHour - 1; } const diff = `${currHour - destHour}:${minute}`; timeDiff = `${diff} hour(s) behind`; } else if (currDateTimeSmplFrmt == destDateTimeSmplFrmt) { const diff = `${currHour - destHour}:${currMinute - destMinute}`; timeDiff = `same as your ${IANA_timezone_source}`; } else if (currDateTimeSmplFrmt < destDateTimeSmplFrmt) { let minute = destMinute - currMinute; if (destHour == '00') { destHour = 24; } if (destMinute < currMinute) { minute = currMinute - destMinute; destHour = destHour - 1; } const diff = `${destHour - currHour}:${minute}`; timeDiff = `${diff} hour(s) ahead`; } // return { offset_from_utc: timeDiff, iana_timezone_of_source: IANA_timezone_source, iana_timezone_of_destination: IANA_timezone_destination }; const searchOffsets = ['UTC', 'GMT']; let standardizedTZ = getTimezoneName(IANA_timezone_destination, 'long'); standardizedTZ = searchOffsets.some(val => standardizedTZ.includes(val)) ? standardizedTZ : 'No UTC/GMT offset'; return { "abbreviation_of_zone": getTimezoneName(IANA_timezone_destination), "standardized_timezone_name": standardizedTZ, // e.g., GMT+5:30 or UTC-10:30 "offset_from_utc": timeDiff, // how many hours behind (or) ahead "iana_timezone_of_source(local)": IANA_timezone_source, //e.g., America/Los_Angeles "iana_timezone_of_destination": IANA_timezone_destination, "daylight name": "" }; } // --------------------------------------------------------- // ------------------------- Features ---------------------- // --------------------------------------------------------- function getDestinationTime(timezone, localeIdentifier) { const date = new Date(); const configOptions = { timeZone: timezone, dateStyle: 'full', timeStyle: 'long' }; const res = new Intl.DateTimeFormat(localeIdentifier ? localeIdentifier : 'en-GB', configOptions).format(date); return res; } function timezoneConverter(IANA_timezone_destination, IANA_timezone_source) { IANA_timezone_source = IANA_timezone_source ? IANA_timezone_source : sourceTimeZone; const currentTime_Dest = getDestinationTime(IANA_timezone_destination); const diff = getTimeDiff(IANA_timezone_destination, IANA_timezone_source); // const actualPath = path.resolve(__dirname, './timezoneConverterOutputs.json'); let fileData = []; // // fetch old data if exists // if(fs.existsSync('./timezoneConverterOutputs.json')) { // const content = fs.readFileSync('./timezoneConverterOutputs.json', 'utf8'); // fileData = JSON.parse(content)[0].data; // } // // append new data fileData.push({ id: fileData.length + 1, currentTime_Dest, diff }); // let obj = [ // { // "data": fileData // } // ] // // write data into json file // fs.writeFile('./timezoneConverterOutputs.json', JSON.stringify(obj, null, " "), 'utf-8', err => { // if (err) throw err; // }); // // return this json file as a output // return obj[0].data; return fileData; } function allTimezones() { return allZoneData.zones; } function timezonesByPlace(place) { const cities = citiesData; const states = statesData; const countries = countriesData; const zones = zoneData; const cityArr = cities[0].data; const stateArr = states[0].data; const countryArr = countries[0].data; const zoneArr = zones; let filterBy = ''; let arrFinalObj = []; if (filterBy == '') { arrFinalObj = []; countryArr.forEach((ele1) => { if (ele1.name.toLowerCase() == place.toLowerCase()) { filterBy = 'from-country'; Object.keys(zoneArr).forEach(z => { if (zoneArr[z].name == ele1.name) { arrFinalObj.push(zoneArr[z]); } }); } }); } if (filterBy == '') { arrFinalObj = []; stateArr.forEach((ele1) => { if (ele1.name.toLowerCase() == place.toLowerCase()) { filterBy = 'from-state'; countryArr.forEach((ele2) => { if (ele2.id == ele1.countryId) { Object.keys(zoneArr).forEach(z => { if (zoneArr[z].name == ele2.name) { arrFinalObj.push(zoneArr[z]); } }); } }); } }); } if (filterBy == '') { arrFinalObj = []; cityArr.forEach((ele1) => { if (ele1.name.toLowerCase() == place.toLowerCase()) { filterBy = 'from-city'; stateArr.forEach((ele2) => { if (ele2.id == ele1.stateId) { countryArr.forEach((ele3) => { if (ele3.id == ele2.countryId) { Object.keys(zoneArr).forEach(z => { if (zoneArr[z].name == ele3.name) { arrFinalObj.push(zoneArr[z]); } }); } }); } }); } }); } let res; place = place.split(' ').join('_'); arrFinalObj.forEach((ele1) => { for (var i = 0; i < ele1.timezones.length; i++) { if (ele1.timezones[i].toLowerCase().includes(place.toLowerCase())) { res = ele1; if (ele1.timezones.length > 1 && filterBy !== 'from-country') { res['mainAns'] = ele1.timezones[i]; } break; } else { if (!res) { res = ele1; if (ele1.timezones.length > 1 && filterBy !== 'from-country') { res['mainAns'] = ele1.timezones[i]; } } } } }); return res; } function getAllCities() { const cities = citiesData; return cities[0].data; } function getAllStates() { const states = statesData; return states[0].data; } function getAllCountries() { const countries = countriesData; return countries[0].data; }