Files
Zos/Skills/@be/node_modules/jibo-data-utils/lib/jibo-data-utils.js

1749 lines
67 KiB
JavaScript

(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jiboDataUtils = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const LocationUtils_1 = require("./LocationUtils");
const Timezone_1 = require("./Timezone");
const jibo_log_1 = require("jibo-log");
let log = new jibo_log_1.Log('Location');
function initLog(parentLog) {
log = parentLog.createChild('Location');
}
exports.initLog = initLog;
const MILES_TO_RADIANS = 1 / 3959;
const BOUNDS_RADIUS = 100 * MILES_TO_RADIANS;
const RADS_TO_DEGREES = 180 / Math.PI;
const DEGREES_TO_RADS = Math.PI / 180;
function moveLatLong(inLat, inLng, distRadians, angleRadians) {
inLat *= DEGREES_TO_RADS;
inLng *= DEGREES_TO_RADS;
let PI = Math.PI;
let lat = Math.asin(Math.sin(inLat) * Math.cos(distRadians) + Math.cos(inLat) * Math.sin(distRadians) * Math.cos(angleRadians));
let lng;
if (Math.cos(lat) === 0) {
lng = inLng;
}
else {
lng = (inLng - Math.asin(Math.sin(angleRadians) * Math.sin(distRadians) / Math.cos(lat)) + PI) % (2 * PI) - PI;
}
return { lat: lat * RADS_TO_DEGREES, lng: lng * RADS_TO_DEGREES };
}
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
}
function areStringsEqual(strA, strB) {
if (strA && !strB) {
return false;
}
if (strB && !strA) {
return false;
}
if (!strA && !strB) {
return true;
}
return strA.toLowerCase() === strB.toLowerCase();
}
let JIBO_HOME = null;
class Location {
static create(city, state, country) {
if (city === 'null') {
city = null;
}
if (state === 'null') {
state = null;
}
if (country === 'null') {
country = null;
}
if (!city && !state && !country) {
return JIBO_HOME;
}
return new Location(city, state, country);
}
constructor(city, state, country) {
if (city === 'null') {
city = null;
}
if (state === 'null') {
state = null;
}
if (country === 'null') {
country = null;
}
this.city = city;
this.stateAbbr = state;
this.state = null;
this.country = country;
this.countryCode = null;
if (!city && state) {
this.city = LocationUtils_1.LocationUtils.getUSStateCapital(state);
}
this.needsTimezone = false;
this.timezone = null;
this.lat = null;
this.lng = null;
this.latLongBounds = null;
this.calculatedRegions = null;
}
static get jiboHome() {
return JIBO_HOME;
}
get isLocal() {
return this.equals(JIBO_HOME);
}
fetch(callback, skipWA = false) {
if (this.lat !== null && this.lng !== null) {
let ll = { lat: this.lat, lng: this.lng };
if (this.needsTimezone && !this.timezone) {
this.timezone = new Timezone_1.default();
this.timezone.fetch(ll, () => {
callback(null, ll);
});
}
else {
callback(null, ll);
}
}
else {
if (!skipWA && !this.city && !this.stateAbbr && this.country) {
LocationUtils_1.LocationUtils.getCountryCapital(this.country)
.then((data) => {
this.city = data.city;
this.state = data.state;
this.country = data.country || this.country;
log.debug('Got capital from WA');
this.fetch(callback);
})
.catch((e) => {
if (e !== LocationUtils_1.LocationUtils.NO_VALID_RESULTS_FROM_WA) {
log.warn('Error looking up capital', e);
}
else {
log.debug('WA did not get us a capital');
}
this.fetch(callback, true);
});
return;
}
let city = this.city;
let address = [city, this.stateAbbr, this.country]
.filter((n) => { return !!n; })
.join(', ');
let opts;
let bounds = JIBO_HOME.getLatLongBounds();
if (bounds) {
opts = { bounds: `${bounds.south.toFixed(12)},${bounds.west.toFixed(12)}|${bounds.north.toFixed(12)},${bounds.east.toFixed(12)}` };
}
LocationUtils_1.LocationUtils.geocode(address, (err, data) => {
if (err) {
log.warn('Error when geocoding: ', err);
callback(err, null);
return;
}
if (!data || !data.results || !data.results.length || !data.results[0].geometry ||
!data.results[0].geometry.location) {
let message = 'Bad geocode results: ';
const jsonData = JSON.stringify(data);
if (!data) {
message += 'no data';
}
else if (!data.results) {
message += 'data does not have results - ' + jsonData;
}
else if (!data.results.length) {
message += 'results is empty - ' + jsonData;
}
else if (!data.results[0].geometry) {
message += 'first result has no geometry - ' + jsonData;
}
else if (!data.results[0].geometry.location) {
message += 'first result has no location - ' + jsonData;
}
log.warn(`On search for ${address}`, message);
callback(message, null);
return;
}
else {
let result = null;
for (let i = 0; i < data.results.length; ++i) {
let types = data.results[i].types;
if (types.indexOf('political') >= 0 &&
(!this.city || types.indexOf('locality') >= 0 ||
types.indexOf('sublocality') >= 0)) {
result = data.results[i];
break;
}
}
if (!result && this.city) {
for (let i = 0; i < data.results.length; ++i) {
let types = data.results[i].address_components[0].types;
if (types.indexOf('political') >= 0 &&
(types.indexOf('administrative_area_level_1') >= 0 ||
types.indexOf('administrative_area_level_2') >= 0)) {
result = data.results[i];
break;
}
}
}
if (!result) {
log.warn('No valid location found: ', data);
callback('no valid location found - ' + JSON.stringify(data), null);
return;
}
let location = result.geometry.location;
this.lat = location.lat;
this.lng = location.lng;
let components = result.address_components;
let foundCity = null;
let foundState = null;
let foundStateAbbr = null;
let foundCountry = null;
let foundCountryCode = null;
for (let i = components.length - 1; i >= 0; --i) {
let comp = components[i];
if (comp.types.indexOf('locality') >= 0 ||
comp.types.indexOf('sublocality') >= 0) {
foundCity = comp.long_name;
}
if (comp.types.indexOf('administrative_area_level_2') >= 0 && !foundCity) {
foundCity = comp.long_name;
}
if (comp.types.indexOf('administrative_area_level_1') >= 0) {
foundState = comp.long_name;
foundStateAbbr = comp.short_name.toLowerCase();
}
if (comp.types.indexOf('country') >= 0) {
foundCountryCode = comp.short_name;
if (foundCountryCode === 'US') {
foundCountry = 'usa';
}
else {
foundCountry = comp.long_name.toLowerCase();
}
}
}
this.city = foundCity;
this.stateAbbr = foundStateAbbr;
if (foundCountryCode === 'US') {
this.state = LocationUtils_1.LocationUtils.getFullState(this.stateAbbr) || foundState;
}
else {
this.state = foundState;
}
if (foundCountry) {
this.country = foundCountry;
this.countryCode = foundCountryCode;
}
if (this.needsTimezone && !this.timezone) {
this.timezone = new Timezone_1.default();
this.timezone.fetch(location, () => {
callback(null, location);
});
}
else {
callback(null, location);
}
}
}, opts);
}
}
isInRegion(regions) {
if (!this.calculatedRegions) {
this.calculatedRegions = this.calculateRegions();
}
if (typeof regions === 'string') {
return this.calculatedRegions.indexOf(regions) > -1;
}
for (let i = 0, length = regions.length; i < length; ++i) {
if (this.calculatedRegions.indexOf(regions[i]) > -1) {
return true;
}
}
return false;
}
equals(loc) {
if (this === loc) {
return true;
}
return (areStringsEqual(this.city, loc.city) &&
areStringsEqual(this.stateAbbr, loc.stateAbbr) &&
areStringsEqual(this.country, loc.country));
}
getStandardName() {
let rtn = '';
if (this.equals(JIBO_HOME)) {
return rtn;
}
if (this.city) {
rtn += this.city;
}
if (this.state && (!this.city || this.countryCode === JIBO_HOME.countryCode || this.countryCode === 'US')) {
if (rtn.length) {
rtn += ' ';
}
rtn += this.state;
}
if (this.country && (this.countryCode !== JIBO_HOME.countryCode && this.countryCode !== 'US')) {
if (rtn.length) {
rtn += ' ';
}
if (this.countryCode === 'US') {
rtn += 'U.S.A.';
}
else {
rtn += this.country;
}
}
return rtn;
}
prefixIn() {
if (this.equals(JIBO_HOME)) {
return '';
}
return 'In ' + this.getStandardName();
}
toString() {
let rtn = '';
if (this.city) {
rtn += toTitleCase(this.city);
}
if (this.state && (!this.city || this.countryCode === JIBO_HOME.countryCode)) {
if (rtn.length) {
rtn += ', ';
}
rtn += this.countryCode === 'US' && this.stateAbbr ? this.stateAbbr.toUpperCase() : this.state;
}
if (this.country && this.countryCode !== JIBO_HOME.countryCode) {
if (rtn.length) {
rtn += ', ';
}
if (this.countryCode === 'US') {
rtn += 'USA';
}
else {
rtn += toTitleCase(this.country);
}
}
return rtn;
}
toLog() {
return `[Location: ${this.toString()}]`;
}
toJSON() {
return {
__type: 'Location',
city: this.city,
state: this.state,
stateAbbr: this.stateAbbr,
country: this.country,
countryCode: this.countryCode,
lat: this.lat,
lng: this.lng,
timezone: this.timezone ? this.timezone.toJSON() : null
};
}
getLatLongBounds() {
if (this.latLongBounds) {
return this.latLongBounds;
}
if (this.lat === null || this.lng === null) {
return null;
}
this.latLongBounds = { north: 0, east: 0, west: 0, south: 0 };
let tempLL = moveLatLong(this.lat, this.lng, BOUNDS_RADIUS, 0);
this.latLongBounds.north = tempLL.lat;
tempLL = moveLatLong(this.lat, this.lng, BOUNDS_RADIUS, Math.PI / 2);
this.latLongBounds.west = tempLL.lng;
tempLL = moveLatLong(this.lat, this.lng, BOUNDS_RADIUS, Math.PI);
this.latLongBounds.south = tempLL.lat;
tempLL = moveLatLong(this.lat, this.lng, BOUNDS_RADIUS, Math.PI * 1.5);
this.latLongBounds.east = tempLL.lng;
return this.latLongBounds;
}
calculateRegions() {
const output = [];
if (this.countryCode) {
output.push(this.countryCode.toUpperCase());
if (this.stateAbbr) {
output.push(`${this.countryCode.toUpperCase()}-${this.stateAbbr.toUpperCase()}`);
}
}
return output;
}
}
exports.default = Location;
JIBO_HOME = new Location();
JIBO_HOME.city = 'boston';
JIBO_HOME.stateAbbr = 'ma';
JIBO_HOME.state = 'Massachusetts';
JIBO_HOME.country = 'usa';
JIBO_HOME.countryCode = 'US';
JIBO_HOME.lat = 42.313352;
JIBO_HOME.lng = -71.1273681;
JIBO_HOME.timezone = new Timezone_1.default({
offsetUTC: -18000000,
name: "Eastern Standard Time",
id: "America/New_York",
__type: "Timezone"
});
function setHome(home) {
JIBO_HOME = home;
}
exports.setHome = setHome;
},{"./LocationUtils":2,"./Timezone":3,"jibo-log":undefined}],2:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = require("axios");
const crypto = require("crypto");
const querystring = require("querystring");
const URLSafeBase64 = require("urlsafe-base64");
let GOOGLE_API = null;
let WOLFRAM_API = null;
const US_STATES = {
al: { name: "Alabama", capital: "Montgomery" },
ak: { name: "Alaska", capital: "Juneau" },
az: { name: "Arizona", capital: "Phoenix" },
ar: { name: "Arkansas", capital: "Little Rock" },
ca: { name: "California", capital: "Sacramento" },
co: { name: "Colorado", capital: "Denver" },
ct: { name: "Connecticut", capital: "Hartford" },
de: { name: "Delaware", capital: "Dover" },
fl: { name: "Florida", capital: "Tallahassee" },
ga: { name: "Georgia", capital: "Atlanta" },
hi: { name: "Hawaii", capital: "Honolulu" },
id: { name: "Idaho", capital: "Boise" },
il: { name: "Illinois", capital: "Springfield" },
in: { name: "Indiana", capital: "Indianapolis" },
ia: { name: "Iowa", capital: "Des Moines" },
ka: { name: "Kansas", capital: "Topeka" },
ky: { name: "Kentucky", capital: "Frankfort" },
la: { name: "Louisiana", capital: "Baton Rouge" },
me: { name: "Maine", capital: "Augusta" },
md: { name: "Maryland", capital: "Annapolis" },
ma: { name: "Massachusetts", capital: "Boston" },
mi: { name: "Michigan", capital: "Lansing" },
mn: { name: "Minnesota", capital: "Saint Paul" },
ms: { name: "Mississippi", capital: "Jackson" },
mo: { name: "Missouri", capital: "Jefferson City" },
mt: { name: "Montana", capital: "Helena" },
ne: { name: "Nebraska", capital: "Lincoln" },
nv: { name: "Nevada", capital: "Carson City" },
nh: { name: "New Hampshire", capital: "Concord" },
nj: { name: "New Jersey", capital: "Trenton" },
nm: { name: "New Mexico", capital: "Santa Fe" },
ny: { name: "New York", capital: "Albany" },
nc: { name: "North Carolina", capital: "Raleigh" },
nd: { name: "North Dakota", capital: "Bismarck" },
oh: { name: "Ohio", capital: "Columbus" },
ok: { name: "Oklahoma", capital: "Oklahoma City" },
or: { name: "Oregon", capital: "Salem" },
pa: { name: "Pennsylvania", capital: "Harrisburg" },
ri: { name: "Rhode Island", capital: "Providence" },
sc: { name: "South Carolina", capital: "Columbia" },
sd: { name: "South Dakota", capital: "Pierre" },
tn: { name: "Tennessee", capital: "Nashville" },
tx: { name: "Texas", capital: "Austin" },
ut: { name: "Utah", capital: "Salt Lake City" },
vt: { name: "Vermont", capital: "Montpelier" },
va: { name: "Virginia", capital: "Richmond" },
wa: { name: "Washington", capital: "Olympia" },
wv: { name: "West Virginia", capital: "Charleston" },
wi: { name: "Wisconsin", capital: "Madison" },
wy: { name: "Wyoming", capital: "Cheyenne" },
as: { name: "American Samoa", capital: "Pago Pago" },
gu: { name: "Guam", capital: "Hagåtña" },
pr: { name: "Puerto Rico", capital: "San Juan" },
vi: { name: "U.S. Virgin Islands", capital: "Charlotte Amalie" },
fm: { name: "Federated States of Micronesia", capital: "Palikir" },
mh: { name: "Marshall Islands", capital: "Majuro" },
pw: { name: "Palau", capital: "Ngerulmud" }
};
class LocationUtils {
static setCapitalLookupKey(key) {
WOLFRAM_API = key;
}
static setLocationLookupKey(key) {
GOOGLE_API = key;
}
static getFullState(abbreviation) {
if (!US_STATES[abbreviation]) {
return "";
}
return US_STATES[abbreviation].name;
}
static getUSStateCapital(abbreviation) {
if (!US_STATES[abbreviation]) {
return "";
}
return US_STATES[abbreviation].capital;
}
static getCountryCapital(country) {
const qs = {
input: country + ' capital',
appid: WOLFRAM_API,
output: "JSON",
podtitle: "Result",
scantimeout: 0.5
};
let url = 'http://api.wolframalpha.com/v2/query?' + querystring.stringify(qs);
return axios_1.default.get(url, { timeout: 8000 })
.then(response => {
let results = response.data;
if (!results) {
throw new Error(LocationUtils.NO_RESULT_FROM_WA);
}
if (typeof results === 'string') {
results = JSON.parse(results);
}
let queryResult = results.queryresult;
if (queryResult && queryResult.success && queryResult.pods) {
if (queryResult.pods[0] &&
queryResult.pods[0].subpods.length > 0 &&
queryResult.pods[0].title === "Result") {
const result = queryResult.pods[0].subpods[0].plaintext.split(',');
let output = {
city: result[0].trim()
};
if (result.length > 1) {
output.country = result[result.length - 1].trim();
}
if (result.length > 2) {
output.state = result[result.length - 2].trim();
}
return output;
}
}
throw new Error(LocationUtils.NO_VALID_RESULTS_FROM_WA);
});
}
static geocode(loc, callback, opts) {
let endpoint = "/maps/api/geocode/json?";
let options = Object.assign({ sensor: false, address: loc, client: "gme-jiboinc" }, opts || {});
options["signature"] = LocationUtils.generateGoogleSignature(GOOGLE_API, endpoint + querystring.stringify(options));
let url = "https://maps.googleapis.com" + endpoint + querystring.stringify(options);
axios_1.default.get(url)
.then(resp => {
let result;
try {
if (typeof resp.data === 'string') {
result = JSON.parse(resp.data);
}
else {
result = resp.data;
}
}
catch (err) {
callback(err, null);
return;
}
callback(null, result);
})
.catch(err => callback(err, null));
}
static generateGoogleSignature(key, req) {
let privateKeyInBuffer = URLSafeBase64.decode(key);
let hashInABuffer = crypto.createHmac('sha1', privateKeyInBuffer).update(req).digest();
let hashEncodedWebSafe = URLSafeBase64.encode(hashInABuffer);
return hashEncodedWebSafe;
}
}
LocationUtils.NO_RESULT_FROM_WA = 'No Result';
LocationUtils.NO_VALID_RESULTS_FROM_WA = 'No Valid Results';
exports.LocationUtils = LocationUtils;
},{"axios":undefined,"crypto":undefined,"querystring":undefined,"urlsafe-base64":undefined}],3:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = require("axios");
const querystring = require("querystring");
const crypto = require("crypto");
const URLSafeBase64 = require("urlsafe-base64");
exports.isoStringParser = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(([+-])(\d\d):(\d\d)|Z)$/;
let GOOGLE_API = null;
function pad(input, length) {
if (typeof input === 'number') {
input = input.toString();
}
while (input.length < length) {
input = '0' + input;
}
return input;
}
class Timezone {
static setLocationLookupKey(key) {
GOOGLE_API = key;
}
static fromISOString(iso) {
const rtn = new Timezone();
if (iso && exports.isoStringParser.test(iso)) {
const [, fullTZ, sign, hour, minute] = iso.match(exports.isoStringParser);
if (fullTZ !== 'Z') {
rtn.offsetUTC = (parseInt(hour) * 60 + parseInt(minute)) * 60 * 1000 * (sign === '-' ? -1 : 1);
}
}
return rtn;
}
constructor(serializedJSON) {
this.offsetUTC = 0;
this.name = "Unknown";
this.id = "Unknown";
if (serializedJSON && serializedJSON.__type === 'Timezone') {
this.offsetUTC = serializedJSON.offsetUTC;
this.name = serializedJSON.name;
this.id = serializedJSON.id;
}
}
fetch(location, callback) {
let timeNow = Math.floor(Date.now() / 1000);
if (GOOGLE_API === null) {
callback('No Google API Key present', null);
}
let endpoint = '/maps/api/timezone/json?';
let options = Object.assign({ timestamp: timeNow, location: `${location.lat},${location.lng}`, client: 'gme-jiboinc' });
options["signature"] = this.generateGoogleSignature(GOOGLE_API, endpoint + querystring.stringify(options));
let url = "https://maps.googleapis.com" + endpoint + querystring.stringify(options);
axios_1.default.get(url)
.then(response => {
let results = response.data;
if (typeof results === 'string') {
results = JSON.parse(results);
}
this.offsetUTC = (results.rawOffset + results.dstOffset) * 1000;
this.name = results.timeZoneName;
this.id = results.timeZoneId;
callback(null, this);
})
.catch(err => callback(err, null));
}
toISOString() {
const offsetMS = this.offsetUTC;
const hours = Math.floor(Math.abs(offsetMS / 1000 / 60 / 60));
const minutes = Math.floor(Math.abs(offsetMS / 1000 / 60 % 60));
return `${offsetMS < 0 ? '-' : '+'}${pad(hours, 2)}:${pad(minutes, 2)}`;
}
toJSON() {
return {
__type: 'Timezone',
offsetUTC: this.offsetUTC,
name: this.name,
id: this.id
};
}
generateGoogleSignature(key, req) {
let privateKeyInBuffer = URLSafeBase64.decode(key);
let hashInABuffer = crypto.createHmac('sha1', privateKeyInBuffer).update(req).digest();
let hashEncodedWebSafe = URLSafeBase64.encode(hashInABuffer);
return hashEncodedWebSafe;
}
}
exports.default = Timezone;
},{"axios":undefined,"crypto":undefined,"querystring":undefined,"urlsafe-base64":undefined}],4:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Timezone_1 = require("../location/Timezone");
const DateTimeUtils_1 = require("./DateTimeUtils");
const relativeDayParser = /^(-?\d+)(d|wd|w|m|y)/i;
const dateParser = /^(\d+)$/;
const monthDateParser = /^(\d?\d)[\/-](\d?\d)$/;
const fullDateParser = /^(\d\d)\/(\d\d)\/(\d\d\d\d)$/;
const dayOfWeekParser = new RegExp('^(' + DateTimeUtils_1.default.DAYS_OF_WEEK.join('|') + ')(_[-+]?\\dw)?$', 'i');
const pastDOWParser = /^_([-+]?\d+)w$/;
const monthNameParser = new RegExp('^(' + DateTimeUtils_1.default.MONTHS.join('|') + ')$', 'i');
const yearParser = /^(\d{4})$/;
const DAY_IN_MS = 24 * 60 * 60 * 1000;
const HOUR_IN_MS = 60 * 60 * 1000;
const timeParser = /(\d+):(\d\d)(AM|PM)*/;
const relativeTimeParser = /^(-?)(\d+)h(\d+)m(\d+)s$/;
function pad(input, length) {
if (typeof input === 'number') {
input = input.toString();
}
while (input.length < length) {
input = '0' + input;
}
return input;
}
var timePeriods;
(function (timePeriods) {
timePeriods["YEAR"] = "year";
timePeriods["MONTH"] = "month";
timePeriods["WEEK"] = "week";
timePeriods["WEEKEND"] = "weekend";
timePeriods["DAY"] = "day";
timePeriods["MORNING"] = "morning";
timePeriods["AFTERNOON"] = "afternoon";
timePeriods["EVENING"] = "evening";
timePeriods["NIGHT"] = "night";
timePeriods["HOUR"] = "hour";
timePeriods["MINUTE"] = "minute";
timePeriods["NOW"] = "now";
})(timePeriods = exports.timePeriods || (exports.timePeriods = {}));
class DateTime {
static get timePeriods() { return timePeriods; }
constructor(input, nluTime, timezone) {
if (nluTime instanceof Timezone_1.default) {
timezone = nluTime;
nluTime = null;
}
this.utc = NaN;
this.timezone = null;
this.durationDays = 0;
this.durationHours = 0;
this.durationMinutes = 0;
this.timePeriod = null;
this._localTime = null;
if (typeof input === 'string' && Timezone_1.isoStringParser.test(input)) {
if (!timezone) {
timezone = Timezone_1.default.fromISOString(input);
}
input = new Date(input).getTime();
}
else if (input instanceof Date) {
input = input.getTime();
}
if (typeof input === 'number') {
this.utc = input;
this.timezone = timezone || new Timezone_1.default();
this.timePeriod = timePeriods.MINUTE;
}
else if (input && input.__type === 'DateTime') {
this.utc = input.utc;
this.timezone = new Timezone_1.default(input.timezone);
this.durationDays = input.durationDays;
this.durationHours = input.durationHours;
this.durationMinutes = input.durationMinutes;
this.timePeriod = input.timePeriod;
}
else if (input || nluTime || timezone) {
this.timezone = timezone || new Timezone_1.default();
this._parseInput(input, nluTime);
}
else {
this.timezone = new Timezone_1.default();
this._parseInput(input, nluTime);
}
}
get utc() {
return this._utc;
}
set utc(value) {
this._utc = value;
this._localTime = null;
}
get timezone() {
return this._timezone;
}
set timezone(value) {
this._timezone = value;
this._localTime = null;
}
clone() {
return new DateTime(this.toJSON());
}
jumpToNextDayPeriod() {
let date = new Date(this.utc + this.timezone.offsetUTC);
let hours = date.getUTCHours();
if (hours < 6) {
date.setUTCHours(6, 0, 0, 0);
this.durationHours = 5;
this.timePeriod = timePeriods.MORNING;
}
else if (hours < 12) {
date.setUTCHours(12, 0, 0, 0);
this.durationHours = 6;
this.timePeriod = timePeriods.AFTERNOON;
}
else if (hours < 18) {
date.setUTCHours(18, 0, 0, 0);
this.durationHours = 4;
this.timePeriod = timePeriods.EVENING;
}
else if (hours < 22) {
date.setUTCHours(22, 0, 0, 0);
this.durationHours = 7;
this.timePeriod = timePeriods.NIGHT;
}
else {
date.setUTCDate(date.getUTCDate() + 1);
date.setUTCHours(6, 0, 0, 0);
}
this.utc = date.getTime() - this.timezone.offsetUTC;
}
addYear(years = 1) {
let date = new Date(this.utc + this.timezone.offsetUTC);
date.setUTCFullYear(date.getUTCFullYear() + years);
this.utc = date.getTime() - this.timezone.offsetUTC;
}
addDays(days, zeroHours = false) {
let date = new Date(this.utc + this.timezone.offsetUTC);
date.setUTCDate(date.getUTCDate() + days);
if (zeroHours) {
date.setUTCHours(0, 0, 0, 0);
this.timePeriod = timePeriods.DAY;
}
this.utc = date.getTime() - this.timezone.offsetUTC;
}
addHours(hours, zeroMinutes = false) {
let date = new Date(this.utc + this.timezone.offsetUTC);
date.setUTCHours(date.getUTCHours() + hours);
if (zeroMinutes) {
date.setUTCMinutes(0, 0, 0);
this.timePeriod = timePeriods.HOUR;
}
this.utc = date.getTime() - this.timezone.offsetUTC;
}
setTime(hours, minutes, seconds = 0, milliseconds = 0) {
let date = new Date(this.utc + this.timezone.offsetUTC);
date.setUTCHours(hours, minutes || 0, seconds, milliseconds);
this.utc = date.getTime() - this.timezone.offsetUTC;
if (minutes !== undefined) {
this.timePeriod = timePeriods.MINUTE;
}
else {
this.timePeriod = timePeriods.HOUR;
}
}
stripTime() {
let timePeriod = this.timePeriod;
if (timePeriod === timePeriods.HOUR || timePeriod === timePeriods.MINUTE ||
timePeriod === timePeriods.MORNING || timePeriod === timePeriods.AFTERNOON ||
timePeriod === timePeriods.EVENING || timePeriod === timePeriods.NIGHT ||
timePeriod === timePeriods.NOW) {
this.timePeriod = timePeriods.DAY;
let date = new Date(this.utc + this.timezone.offsetUTC);
date.setUTCHours(0, 0, 0, 0);
this.utc = date.getTime() - this.timezone.offsetUTC;
this.durationHours = this.durationMinutes = 0;
}
}
isPast() {
let endTime = this._utc;
if (this.timePeriod === timePeriods.YEAR) {
const endDate = new Date(endTime);
endDate.setUTCFullYear(endDate.getUTCFullYear() + 1);
endTime = endDate.getTime();
}
else if (this.timePeriod === timePeriods.MONTH) {
const endDate = new Date(endTime);
endDate.setUTCMonth(endDate.getUTCMonth() + 1);
endTime = endDate.getTime();
}
else if (this.timePeriod === timePeriods.DAY) {
const endDate = new Date(endTime);
endDate.setUTCDate(endDate.getUTCDate() + 1);
endTime = endDate.getTime();
}
if (this.durationDays) {
endTime += this.durationDays * DAY_IN_MS;
}
if (this.durationHours) {
endTime += this.durationHours * HOUR_IN_MS;
}
if (this.durationMinutes) {
endTime += this.durationMinutes * 60 * 1000;
}
return endTime < Date.now();
}
isFuture() {
return this._utc > Date.now();
}
isInRange(startDate, endDate) {
try {
const start = monthDateParser.exec(startDate);
const end = monthDateParser.exec(endDate);
const startMonth = parseInt(start[1]) - 1;
const startDay = parseInt(start[2]);
const endMonth = parseInt(end[1]) - 1;
const endDay = parseInt(end[2]);
const { monthNum, date } = this.getLocalTime();
if (endMonth < startMonth || (endMonth === startMonth && endDay < startDay)) {
if (startMonth > monthNum && endMonth < monthNum) {
return false;
}
if (startMonth === endMonth && monthNum === startMonth &&
(date > startDay || date < endDay)) {
return true;
}
if ((monthNum === startMonth && date < startDay) ||
(monthNum === endMonth && date > endDay)) {
return false;
}
return true;
}
else {
if (monthNum < startMonth || monthNum > endMonth) {
return false;
}
if ((monthNum === startMonth && date < startDay) ||
(monthNum === endMonth && date > endDay)) {
return false;
}
return true;
}
}
catch (e) {
console.error(e);
return false;
}
}
getLocalTime() {
if (!this._localTime) {
const localDate = new Date(this.utc + this.timezone.offsetUTC);
const month = localDate.getUTCMonth();
this._localTime = {
year: localDate.getUTCFullYear(),
month: DateTimeUtils_1.default.MONTHS[month],
monthNum: month,
dayOfWeek: DateTimeUtils_1.default.DAYS_OF_WEEK[localDate.getUTCDay()],
date: localDate.getUTCDate(),
hour: localDate.getUTCHours(),
minute: localDate.getUTCMinutes(),
seconds: localDate.getUTCSeconds(),
milliseconds: localDate.getUTCMilliseconds()
};
}
return this._localTime;
}
getLocalMMDD() {
let rtn = '';
let date = new Date(this.utc + this.timezone.offsetUTC);
let month = date.getUTCMonth() + 1;
rtn += month < 10 ? '0' + month : month;
let day = date.getUTCDate();
rtn += day < 10 ? '0' + day : day;
return rtn;
}
getLocalYYYYMMDD() {
let rtn = '';
let date = new Date(this.utc + this.timezone.offsetUTC);
rtn += date.getUTCFullYear();
let month = date.getUTCMonth() + 1;
rtn += month < 10 ? '0' + month : month;
let day = date.getUTCDate();
rtn += day < 10 ? '0' + day : day;
return rtn;
}
getRelativeDays() {
let thisDate = new Date(this.utc + this.timezone.offsetUTC);
let utc1 = Date.UTC(thisDate.getUTCFullYear(), thisDate.getUTCMonth(), thisDate.getUTCDate());
let now = new Date(Date.now() + this.timezone.offsetUTC);
let utc2 = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
return Math.floor((utc1 - utc2) / DAY_IN_MS + 0.1);
}
getRelativeHours() {
let thisDate = new Date(this.utc + this.timezone.offsetUTC);
let utc1 = Date.UTC(thisDate.getUTCFullYear(), thisDate.getUTCMonth(), thisDate.getUTCDate(), thisDate.getUTCHours());
let now = new Date(Date.now() + this.timezone.offsetUTC);
let utc2 = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours());
return Math.floor((utc1 - utc2) / HOUR_IN_MS + 0.1);
}
toString(options) {
if (!options) {
options = {};
}
if (options.suppressVerbalOutput) {
return '';
}
let rtn = '';
let thisDate = new Date(this.utc + this.timezone.offsetUTC);
let relativeDays = this.getRelativeDays();
let timePeriod = this.timePeriod;
let wasLongPeriod = false;
if (timePeriod === timePeriods.YEAR || timePeriod === timePeriods.MONTH ||
timePeriod === timePeriods.WEEK || timePeriod === timePeriods.WEEKEND) {
wasLongPeriod = true;
let targetWeek, nowWeek, daysDiff, weeksDiff;
switch (this.timePeriod) {
case timePeriods.YEAR:
rtn = String(thisDate.getUTCFullYear());
break;
case timePeriods.MONTH:
rtn = DateTimeUtils_1.default.MONTHS[thisDate.getUTCMonth()];
break;
case timePeriods.WEEK:
targetWeek = new Date(this.utc + this.timezone.offsetUTC);
targetWeek.setUTCDate(targetWeek.getUTCDate() - targetWeek.getUTCDay() + 1);
nowWeek = new Date(Date.now() + this.timezone.offsetUTC);
nowWeek.setUTCDate(nowWeek.getUTCDate() - nowWeek.getUTCDay() + 1);
daysDiff = DateTimeUtils_1.default.getDaysBetweenDates(nowWeek, targetWeek);
weeksDiff = Math.round(daysDiff / 7);
if (weeksDiff === 0) {
rtn = 'this week';
}
else if (weeksDiff > 0) {
if (weeksDiff === 1) {
rtn = 'next week';
}
else {
rtn = weeksDiff + ' weeks from now';
}
}
else {
if (weeksDiff === -1) {
rtn = 'last week';
}
else {
rtn = Math.abs(weeksDiff) + ' weeks ago';
}
}
break;
case timePeriods.WEEKEND:
targetWeek = new Date(this.utc + this.timezone.offsetUTC);
targetWeek.setUTCDate(targetWeek.getUTCDate() - targetWeek.getUTCDay() + 6);
nowWeek = new Date(Date.now() + this.timezone.offsetUTC);
nowWeek.setUTCDate(nowWeek.getUTCDate() - nowWeek.getUTCDay() + 6);
daysDiff = DateTimeUtils_1.default.getDaysBetweenDates(nowWeek, targetWeek);
weeksDiff = Math.round(daysDiff / 7);
if (weeksDiff === 0) {
rtn = 'this weekend';
}
else if (weeksDiff > 0) {
if (weeksDiff === 1) {
rtn = 'next weekend';
}
else {
rtn = weeksDiff + ' weekends from now';
}
}
else {
if (weeksDiff === -1) {
rtn = 'last weekend';
}
else {
rtn = Math.abs(weeksDiff) + ' weekends ago';
}
}
break;
}
}
let usedDate = false;
if (!wasLongPeriod && !options.timeOnly) {
if (timePeriod === timePeriods.DAY || relativeDays !== 0 || options.dateOnly) {
if (relativeDays === 0) {
rtn = 'today';
}
else if (relativeDays === -1) {
rtn = 'yesterday';
}
else if (relativeDays === 1) {
rtn = 'tomorrow';
}
else if (relativeDays < 7 && relativeDays > 0) {
rtn = DateTimeUtils_1.default.DAYS_OF_WEEK[thisDate.getUTCDay()];
}
else {
usedDate = true;
rtn = DateTimeUtils_1.default.MONTHS[thisDate.getUTCMonth()];
rtn += ' ' + DateTimeUtils_1.default.getOrdinal(thisDate.getUTCDate());
let now = new Date(Date.now() + this.timezone.offsetUTC);
if (now.getUTCFullYear() !== thisDate.getUTCFullYear()) {
rtn += ' ' + thisDate.getUTCFullYear();
}
}
}
}
if (!wasLongPeriod && !options.dateOnly) {
if (timePeriod === timePeriods.MORNING) {
if (usedDate) {
rtn = 'morning of ' + rtn;
}
else if (relativeDays === 0) {
rtn = 'this morning';
}
else {
rtn += ' morning';
}
}
else if (timePeriod === timePeriods.AFTERNOON) {
if (usedDate) {
rtn = 'afternoon of ' + rtn;
}
else if (relativeDays === 0) {
rtn = 'this afternoon';
}
else {
rtn += ' afternoon';
}
}
else if (timePeriod === timePeriods.EVENING) {
if (usedDate) {
rtn = 'evening of ' + rtn;
}
else if (relativeDays === 0) {
rtn = 'this evening';
}
else {
rtn += ' evening';
}
}
else if (timePeriod === timePeriods.NIGHT) {
if (usedDate) {
rtn = 'night of ' + rtn;
}
else if (relativeDays === 0) {
rtn = 'tonight';
}
else if (relativeDays === -1) {
rtn = 'last night';
}
else {
rtn += ' night';
}
}
if (timePeriod === timePeriods.HOUR || timePeriod === timePeriods.MINUTE || timePeriod === timePeriods.NOW) {
if (relativeDays !== 0 && !options.timeOnly) {
rtn += ' at ';
}
if (options.display) {
rtn += DateTimeUtils_1.default.getVisualTime(thisDate.getUTCHours(), thisDate.getUTCMinutes(), options.dropPeriod);
}
else {
rtn += DateTimeUtils_1.default.getVerbalTime(thisDate.getUTCHours(), thisDate.getUTCMinutes(), options.dropPeriod);
}
}
}
if (options.prefixOnAt) {
if (timePeriod === timePeriods.YEAR || timePeriod === timePeriods.MONTH) {
rtn = 'in ' + rtn;
}
else if (timePeriod === timePeriods.WEEK || timePeriod === timePeriods.WEEKEND) {
}
else if (!options.dateOnly &&
(timePeriod === timePeriods.HOUR || timePeriod === timePeriods.MINUTE ||
timePeriod === timePeriods.NOW || options.timeOnly)) {
if (relativeDays === 0 || options.timeOnly) {
rtn = 'at ' + rtn;
}
else if (relativeDays === -1 || relativeDays === 1) {
}
else {
rtn = 'on ' + rtn;
}
}
else if (relativeDays === 0 || relativeDays === -1 || relativeDays === 1) {
}
else {
rtn = 'on ' + rtn;
}
}
return rtn;
}
prefixOnAt(options) {
if (!options) {
options = {};
}
options.prefixOnAt = true;
return this.toString(options);
}
toMoment() {
if (Date.now() - this._utc < 0) {
return 'The Future';
}
const diffInMin = (Date.now() - this._utc) / (1000 * 60);
if (diffInMin <= 30) {
return 'Just Now';
}
if (diffInMin <= 60) {
return `${Math.floor(diffInMin)}m ago`;
}
const diffInHours = diffInMin / 60;
if (diffInHours <= 24) {
return `${Math.floor(diffInHours)}h ago`;
}
const relativeDays = -this.getRelativeDays();
if (relativeDays <= 7) {
return relativeDays === 1 ? 'Yesterday' : `${relativeDays}d ago`;
}
const local = this.getLocalTime();
const now = new DateTime(Date.now(), this._timezone).getLocalTime();
let date = DateTimeUtils_1.default.MONTH_ABBREVIATIONS[local.monthNum] + ' ';
if (local.year === now.year) {
date += DateTimeUtils_1.default.getOrdinal(local.date);
}
else {
date += local.date + ' ' + local.year;
}
return date;
}
toJSON() {
return {
__type: 'DateTime',
utc: this.utc,
timezone: this.timezone.toJSON(),
durationDays: this.durationDays,
durationHours: this.durationHours,
durationMinutes: this.durationMinutes,
timePeriod: this.timePeriod
};
}
toISOString() {
const local = this.getLocalTime();
return `${pad(local.year, 4)}-${pad((local.monthNum + 1), 2)}-${pad(local.date, 2)}T${pad(local.hour, 2)}:${pad(local.minute, 2)}:${pad(local.seconds, 2)}.${pad(local.milliseconds, 3)}` + this._timezone.toISOString();
}
toLog() {
return this.toJSON();
}
_parseInput(nluDate, nluTime) {
if (nluDate === 'null') {
nluDate = null;
}
if (nluTime === 'null') {
nluTime = null;
}
let dateUTC = null;
let dayNotSpecified = false;
let isToday = false;
if (!nluDate) {
dateUTC = new Date(Date.now() + this.timezone.offsetUTC);
dayNotSpecified = true;
isToday = true;
}
else if (relativeDayParser.test(nluDate)) {
dateUTC = new Date(Date.now() + this.timezone.offsetUTC);
let regexResult = relativeDayParser.exec(nluDate);
if (regexResult[2] === 'd') {
let relativeDay = parseInt(regexResult[1], 10);
if (relativeDay !== 0) {
dateUTC.setUTCDate(dateUTC.getUTCDate() + relativeDay);
}
else {
isToday = true;
}
this.timePeriod = timePeriods.DAY;
}
else if (regexResult[2] === 'wd') {
let numWeeksAhead = parseInt(regexResult[1], 10);
let dayOfWeek = dateUTC.getUTCDay();
let relativeDay = numWeeksAhead * 7 + (6 - dayOfWeek);
if (dayOfWeek === 0) {
relativeDay -= 7;
}
if (relativeDay !== 0) {
dateUTC.setUTCDate(dateUTC.getUTCDate() + relativeDay);
}
this.durationDays = 2;
this.timePeriod = timePeriods.WEEKEND;
}
else if (regexResult[2] === 'w') {
let numWeeksAhead = parseInt(regexResult[1], 10);
let dayOfWeek = dateUTC.getUTCDay();
let relativeDay = numWeeksAhead * 7 - dayOfWeek + 1;
if (relativeDay !== 0) {
dateUTC.setUTCDate(dateUTC.getUTCDate() + relativeDay);
}
this.durationDays = 7;
this.timePeriod = timePeriods.WEEK;
}
else if (regexResult[2] === 'm') {
let relativeMonth = parseInt(regexResult[1], 10);
dateUTC.setUTCMonth(dateUTC.getUTCMonth() + relativeMonth, 1);
this.timePeriod = timePeriods.MONTH;
}
else if (regexResult[2] === 'y') {
let relativeYear = parseInt(regexResult[1], 10) * 365;
dateUTC.setUTCFullYear(dateUTC.getUTCFullYear() + relativeYear, 0, 1);
this.timePeriod = timePeriods.YEAR;
}
}
else if (dateParser.test(nluDate)) {
dateUTC = new Date(Date.now() + this.timezone.offsetUTC);
let date = parseInt(dateParser.exec(nluDate)[1], 10);
let daysInCurrentMonth = new Date(dateUTC.getUTCFullYear(), dateUTC.getUTCMonth() + 1, 0).getUTCDate();
if (dateUTC.getUTCDate() < date && date <= daysInCurrentMonth) {
dateUTC.setUTCDate(date);
}
else {
dateUTC.setUTCMonth(dateUTC.getUTCMonth() + 1);
dateUTC.setUTCDate(date);
}
this.timePeriod = timePeriods.DAY;
}
else if (monthDateParser.test(nluDate)) {
let regexResult = monthDateParser.exec(nluDate);
dateUTC = new Date(Date.now() + this.timezone.offsetUTC);
let month = parseInt(regexResult[1], 10) - 1;
let date = parseInt(regexResult[2], 10);
let nowMonth = dateUTC.getUTCMonth();
if (month < nowMonth || (month === nowMonth && date < dateUTC.getUTCDate())) {
dateUTC.setUTCFullYear(dateUTC.getUTCFullYear() + 1);
}
dateUTC.setUTCMonth(month);
dateUTC.setUTCDate(date);
this.timePeriod = timePeriods.DAY;
}
else if (fullDateParser.test(nluDate)) {
let regexResult = fullDateParser.exec(nluDate);
dateUTC = new Date(Date.UTC(parseInt(regexResult[3], 10), parseInt(regexResult[1], 10) - 1, parseInt(regexResult[2], 10)));
this.timePeriod = timePeriods.DAY;
}
else if (dayOfWeekParser.test(nluDate)) {
let regexResult = dayOfWeekParser.exec(nluDate);
let dow = regexResult[1];
dateUTC = new Date(Date.now() + this.timezone.offsetUTC);
let relativeDay = DateTimeUtils_1.default.DAYS_OF_WEEK[dow] - dateUTC.getUTCDay();
if (relativeDay < 0) {
relativeDay += 7;
}
if (pastDOWParser.test(regexResult[2])) {
regexResult = pastDOWParser.exec(regexResult[2]);
let weeksDiff = parseInt(regexResult[1], 10);
relativeDay += weeksDiff * 7;
}
if (relativeDay !== 0) {
dateUTC.setUTCDate(dateUTC.getUTCDate() + relativeDay);
}
else {
isToday = true;
}
this.timePeriod = timePeriods.DAY;
}
else if (monthNameParser.test(nluDate)) {
let regexResult = monthNameParser.exec(nluDate);
let monthNum = DateTimeUtils_1.default.MONTHS.indexOf(regexResult[1].toLowerCase());
dateUTC = new Date(Date.now() + this.timezone.offsetUTC);
if (monthNum < dateUTC.getUTCMonth()) {
dateUTC.setUTCFullYear(dateUTC.getUTCFullYear() + 1, monthNum, 1);
}
else {
dateUTC.setUTCMonth(monthNum, 1);
}
this.timePeriod = timePeriods.MONTH;
}
else if (yearParser.test(nluDate)) {
let regexResult = yearParser.exec(nluDate);
dateUTC.setUTCFullYear(parseInt(regexResult[1], 10), 0, 1);
this.timePeriod = timePeriods.YEAR;
}
if (!nluTime) {
if (dayNotSpecified) {
this.timePeriod = timePeriods.NOW;
}
else {
dateUTC.setUTCHours(0, 0, 0, 0);
}
}
else {
if (nluTime === 'noon') {
dateUTC.setUTCHours(12, 0, 0, 0);
this.timePeriod = timePeriods.HOUR;
}
else if (nluTime === 'midnight') {
dateUTC.setUTCHours(24, 0, 0, 0);
this.timePeriod = timePeriods.HOUR;
}
else if (nluTime === 'morning') {
dateUTC.setUTCHours(6, 0, 0, 0);
this.durationHours = 5;
this.timePeriod = timePeriods.MORNING;
}
else if (nluTime === 'afternoon') {
dateUTC.setUTCHours(12, 0, 0, 0);
this.durationHours = 6;
this.timePeriod = timePeriods.AFTERNOON;
}
else if (nluTime === 'evening') {
dateUTC.setUTCHours(18, 0, 0, 0);
this.durationHours = 4;
this.timePeriod = timePeriods.EVENING;
}
else if (nluTime === 'night') {
dateUTC.setUTCHours(22, 0, 0, 0);
this.durationHours = 7;
this.timePeriod = timePeriods.NIGHT;
}
else if (timeParser.test(nluTime)) {
let timeSplit = timeParser.exec(nluTime);
let hoursIn12H = parseInt(timeSplit[1], 10);
let minutes = parseInt(timeSplit[2], 10);
switch (timeSplit[3]) {
case 'AM':
if (hoursIn12H === 12) {
dateUTC.setUTCHours(0);
}
else {
dateUTC.setUTCHours(hoursIn12H);
}
break;
case 'PM':
if (hoursIn12H !== 12) {
dateUTC.setUTCHours(hoursIn12H + 12);
}
else {
dateUTC.setUTCHours(hoursIn12H);
}
break;
default:
if (hoursIn12H === 12 || hoursIn12H < 6) {
let hoursIn24H = hoursIn12H === 12 ? hoursIn12H : hoursIn12H + 12;
if (dayNotSpecified) {
let nowHour = dateUTC.getUTCHours();
let nowMinutes = dateUTC.getUTCMinutes();
if (nowHour > hoursIn24H ||
(nowHour === hoursIn24H && nowMinutes >= minutes)) {
dateUTC.setUTCDate(dateUTC.getUTCDate() + 1);
dateUTC.setUTCHours(hoursIn24H);
}
else {
dateUTC.setUTCHours(hoursIn24H);
}
}
else {
dateUTC.setUTCHours(hoursIn24H);
}
}
else if (isToday) {
let nowHour = dateUTC.getUTCHours();
let nowMinutes = dateUTC.getUTCMinutes();
if (nowHour < 12) {
if (hoursIn12H > nowHour ||
(hoursIn12H === nowHour && minutes > nowMinutes)) {
dateUTC.setUTCHours(hoursIn12H);
}
else {
dateUTC.setUTCHours(hoursIn12H + 12);
}
}
else {
let hoursIn24H = hoursIn12H === 12 ? hoursIn12H : hoursIn12H + 12;
if (hoursIn24H < nowHour ||
(hoursIn24H === nowHour && minutes < nowMinutes)) {
if (dayNotSpecified) {
dateUTC.setUTCDate(dateUTC.getUTCDate() + 1);
dateUTC.setUTCHours(hoursIn12H);
}
else {
dateUTC.setUTCHours(hoursIn24H);
}
}
else {
dateUTC.setUTCHours(hoursIn24H);
}
}
}
else {
dateUTC.setUTCHours(hoursIn12H);
}
}
dateUTC.setUTCMinutes(minutes, 0, 0);
this.timePeriod = minutes === 0 ? timePeriods.HOUR : timePeriods.MINUTE;
}
else if (relativeTimeParser.test(nluTime)) {
let regexResult = relativeTimeParser.exec(nluTime);
let relativeHours = parseInt(regexResult[2], 10);
let relativeMinutes = parseInt(regexResult[3], 10);
let relativeSeconds = parseInt(regexResult[4], 10);
if (regexResult[1] === '-') {
relativeHours = -relativeHours;
relativeMinutes = -relativeMinutes;
relativeSeconds = -relativeSeconds;
}
if (relativeHours !== 0) {
dateUTC.setUTCHours(dateUTC.getUTCHours() + relativeHours);
}
if (relativeMinutes !== 0) {
dateUTC.setUTCMinutes(dateUTC.getUTCMinutes() + relativeMinutes);
}
if (relativeSeconds !== 0) {
dateUTC.setUTCSeconds(dateUTC.getUTCSeconds() + relativeSeconds);
}
this.timePeriod = timePeriods.MINUTE;
}
}
this.utc = dateUTC.getTime() - this.timezone.offsetUTC;
}
}
exports.default = DateTime;
},{"../location/Timezone":3,"./DateTimeUtils":5}],5:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DateTimeUtils;
(function (DateTimeUtils) {
DateTimeUtils.MONTHS = [
'january',
'february',
'march',
'april',
'may',
'june',
'july',
'august',
'september',
'october',
'november',
'december'
];
DateTimeUtils.MONTH_ABBREVIATIONS = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
DateTimeUtils.DAYS_OF_WEEK = [
'sunday',
'monday',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday'
];
DateTimeUtils.MS_PER_DAY = 1000 * 60 * 60 * 24;
let DiffUnit;
(function (DiffUnit) {
DiffUnit[DiffUnit["Milliseconds"] = 0] = "Milliseconds";
DiffUnit[DiffUnit["Seconds"] = 1] = "Seconds";
DiffUnit[DiffUnit["Minutes"] = 2] = "Minutes";
DiffUnit[DiffUnit["Hours"] = 3] = "Hours";
DiffUnit[DiffUnit["Days"] = 4] = "Days";
DiffUnit[DiffUnit["Weeks"] = 5] = "Weeks";
})(DiffUnit = DateTimeUtils.DiffUnit || (DateTimeUtils.DiffUnit = {}));
function getVerbalNumber(input) {
if (input === 0) {
return 'zero';
}
let returnVal = input < 0 ? 'negative ' : '';
input = Math.abs(input);
let tens = input / 10 | 0;
let ones = input % 10 | 0;
switch (tens) {
case 1:
switch (ones) {
case 0:
returnVal += 'ten';
break;
case 1:
returnVal += 'eleven';
break;
case 2:
returnVal += 'twelve';
break;
case 3:
returnVal += 'thirteen';
break;
case 4:
returnVal += 'fourteen';
break;
case 5:
returnVal += 'fifteen';
break;
case 6:
returnVal += 'sixteen';
break;
case 7:
returnVal += 'seventeen';
break;
case 8:
returnVal += 'eighteen';
break;
case 9:
returnVal += 'nineteen';
break;
}
break;
case 2:
returnVal += 'twenty';
break;
case 3:
returnVal += 'thirty';
break;
case 4:
returnVal += 'forty';
break;
case 5:
returnVal += 'fifty';
break;
case 6:
returnVal += 'sixty';
break;
case 7:
returnVal += 'seventy';
break;
case 8:
returnVal += 'eighty';
break;
case 9:
returnVal += 'ninety';
break;
}
if (tens !== 1) {
if (tens !== 0 && ones !== 0) {
returnVal += ' ';
}
switch (ones) {
case 1:
returnVal += 'one';
break;
case 2:
returnVal += 'two';
break;
case 3:
returnVal += 'three';
break;
case 4:
returnVal += 'four';
break;
case 5:
returnVal += 'five';
break;
case 6:
returnVal += 'six';
break;
case 7:
returnVal += 'seven';
break;
case 8:
returnVal += 'eight';
break;
case 9:
returnVal += 'nine';
break;
}
}
return returnVal;
}
DateTimeUtils.getVerbalNumber = getVerbalNumber;
function getOrdinal(num) {
if (num === 0) {
return 'zero';
}
if (num < 20 && num > 10) {
return String(num) + 'th';
}
switch (num % 10) {
case 1:
return String(num) + 'st';
case 2:
return String(num) + 'nd';
case 3:
return String(num) + 'rd';
default:
return String(num) + 'th';
}
}
DateTimeUtils.getOrdinal = getOrdinal;
function getVerbalTime(hour, minute = 0, dropPeriod = false) {
if (dropPeriod) {
if (hour >= 12) {
if (hour > 12) {
hour -= 12;
}
}
else if (hour === 0) {
hour = 12;
}
let time = getVerbalNumber(hour) + ' ';
if (minute === 0) {
time += 'oh clock';
}
else if (minute < 10) {
time += 'oh ' + getVerbalNumber(minute);
}
else {
time += getVerbalNumber(minute);
}
return time;
}
else {
return getVisualTime(hour, minute);
}
}
DateTimeUtils.getVerbalTime = getVerbalTime;
function getVisualTime(hour, minute, dropPeriod = false) {
let period = 'AM';
if (hour >= 12) {
period = 'PM';
if (hour > 12) {
hour -= 12;
}
}
else if (hour === 0) {
hour = 12;
}
let minuteName = '';
if (minute !== null) {
minuteName = ':';
minute = minute || 0;
if (minute < 10) {
minuteName += '0';
}
minuteName += minute;
}
let hourName = String(hour === 0 ? 12 : hour);
if (dropPeriod) {
return `${hourName}${minuteName}`;
}
return `${hourName}${minuteName} ${period}`;
}
DateTimeUtils.getVisualTime = getVisualTime;
function getVerbalTimeFrom24Hour(time) {
return getVerbalTime(parseInt(time.substr(0, 2), 10), parseInt(time.substr(2, 2), 10));
}
DateTimeUtils.getVerbalTimeFrom24Hour = getVerbalTimeFrom24Hour;
function getVisualTimeFrom24Hour(time) {
return getVisualTime(parseInt(time.substr(0, 2), 10), parseInt(time.substr(2, 2), 10));
}
DateTimeUtils.getVisualTimeFrom24Hour = getVisualTimeFrom24Hour;
function getDaysBetweenDates(a, b) {
const utc1 = Date.UTC(a.getUTCFullYear(), a.getUTCMonth(), a.getUTCDate());
const utc2 = Date.UTC(b.getUTCFullYear(), b.getUTCMonth(), b.getUTCDate());
return Math.floor((utc2 - utc1) / this.MS_PER_DAY + 0.1);
}
DateTimeUtils.getDaysBetweenDates = getDaysBetweenDates;
function diffDateTimes(a, b, unit = DiffUnit.Milliseconds) {
let diff = b.utc - a.utc;
if (unit > DiffUnit.Milliseconds) {
diff /= 1000;
}
if (unit > DiffUnit.Seconds) {
diff /= 60;
}
if (unit > DiffUnit.Minutes) {
diff /= 60;
}
if (unit > DiffUnit.Hours) {
diff /= 24;
}
if (unit > DiffUnit.Days) {
diff /= 7;
}
return diff;
}
DateTimeUtils.diffDateTimes = diffDateTimes;
})(DateTimeUtils || (DateTimeUtils = {}));
exports.default = DateTimeUtils;
},{}],6:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Timezone_1 = require("./location/Timezone");
exports.Timezone = Timezone_1.default;
var DateTime_1 = require("./time/DateTime");
exports.DateTime = DateTime_1.default;
var DateTimeUtils_1 = require("./time/DateTimeUtils");
exports.DateTimeUtils = DateTimeUtils_1.default;
var Location_1 = require("./location/Location");
exports.Location = Location_1.default;
exports.setHome = Location_1.setHome;
var LocationUtils_1 = require("./location/LocationUtils");
exports.LocationUtils = LocationUtils_1.LocationUtils;
const Location_2 = require("./location/Location");
function initLog(parentLog) {
Location_2.initLog(parentLog);
}
exports.initLog = initLog;
},{"./location/Location":1,"./location/LocationUtils":2,"./location/Timezone":3,"./time/DateTime":4,"./time/DateTimeUtils":5}]},{},[6])(6)
});
//# sourceMappingURL=jibo-data-utils.js.map