@onesy/date
Version:
Time and date utils library
1,348 lines (1,146 loc) • 129 kB
JavaScript
/** @license Date v1.0.2
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Date = {}));
})(this, (function (exports) { 'use strict';
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var merge$1 = {};
var global$1 = (typeof global !== "undefined" ? global :
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window : {});
var is$3 = {exports: {}};
(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
const optionsDefault = {};
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
const isNodejs = !!(typeof global$1 !== 'undefined' && 'object' !== 'undefined' && module.exports);
// Multiple is methods instead of one,
// so it's lighter for tree shaking usability reasons
function is(type, value, options_ = {}) {
var _a;
const options = Object.assign(Object.assign({}, optionsDefault), options_);
const { variant } = options;
const prototype = value && typeof value === 'object' && Object.getPrototypeOf(value);
switch (type) {
case 'string':
return typeof value === 'string';
case 'number':
return typeof value === 'number' && !Number.isNaN(value);
case 'boolean':
return typeof value === 'boolean';
case 'array':
return Array.isArray(value);
case 'object':
const isObject = typeof value === 'object' && !!value && value.constructor === Object;
return isObject;
// Map, null, WeakMap, Date, etc.
case 'object-like':
return typeof value === 'object' && (value === null || value.constructor !== Object);
case 'class':
return ((typeof value === 'object' || typeof value === 'function') &&
(/class/gi.test(String(value)) || /class/gi.test(String(value === null || value === void 0 ? void 0 : value.constructor))));
case 'function':
return !!(value && value instanceof Function);
case 'async':
// If it's browser avoid calling the method
// to see if it's async func or not,
// where as in nodejs we have no other choice
// that i know of when using transpilation
// And also it might not be always correct, as
// a method that returns a promise is also async
// but we can't know that until the method is called and
// we inspect the method's return value
return !!(is('function', value) && (isBrowser ? value.constructor.name === 'AsyncFunction' : value() instanceof Promise));
case 'map':
return !!(prototype === Map.prototype);
case 'weakmap':
return !!(prototype === WeakMap.prototype);
case 'set':
return !!(prototype === Set.prototype);
case 'weakset':
return !!(prototype === WeakSet.prototype);
case 'promise':
return !!(prototype === Promise.prototype);
case 'int8array':
return !!(prototype === Int8Array.prototype);
case 'uint8array':
return !!(prototype === Uint8Array.prototype);
case 'uint8clampedarray':
return !!(prototype === Uint8ClampedArray.prototype);
case 'int16array':
return !!(prototype === Int16Array.prototype);
case 'uint16array':
return !!(prototype === Uint16Array.prototype);
case 'int32array':
return !!(prototype === Int32Array.prototype);
case 'uint32array':
return !!(prototype === Uint32Array.prototype);
case 'float32array':
return !!(prototype === Float32Array.prototype);
case 'float64array':
return !!(prototype === Float64Array.prototype);
case 'bigint64array':
return !!(prototype === BigInt64Array.prototype);
case 'biguint64array':
return !!(prototype === BigUint64Array.prototype);
case 'typedarray':
return is('int8array', value) || is('uint8array', value) || is('uint8clampedarray', value) || is('int16array', value) || is('uint16array', value) || is('int32array', value) || is('uint32array', value) || is('float32array', value) || is('float64array', value) || is('bigint64array', value) || is('biguint64array', value);
case 'dataview':
return !!(prototype === DataView.prototype);
case 'arraybuffer':
return !!(prototype === ArrayBuffer.prototype);
case 'sharedarraybuffer':
return typeof SharedArrayBuffer !== 'undefined' && !!(prototype === SharedArrayBuffer.prototype);
case 'symbol':
return !!(typeof value === 'symbol');
case 'error':
return !!(value && value instanceof Error);
case 'date':
return !!(value && value instanceof Date);
case 'regexp':
return !!(value && value instanceof RegExp);
case 'arguments':
return !!(value && value.toString() === '[object Arguments]');
case 'null':
return value === null;
case 'undefined':
return value === undefined;
case 'blob':
return isBrowser && value instanceof Blob;
case 'buffer':
return !!(isNodejs && typeof ((_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? void 0 : _a.isBuffer) === 'function' && value.constructor.isBuffer(value));
case 'element':
if (value) {
switch (variant) {
case undefined:
case 'html':
case 'element':
return isBrowser && (typeof HTMLElement === 'object' ?
value instanceof HTMLElement :
value && typeof value === 'object' && value !== null && value.nodeType === 1 && typeof value.nodeName === 'string');
case 'node':
return isBrowser && (typeof Node === 'object' ?
value instanceof Node :
value && typeof value === 'object' && value !== null && typeof value.nodeType === 'number' && typeof value.nodeName === 'string');
case 'react':
return value.elementType || value.hasOwnProperty('$$typeof');
default:
return false;
}
}
return false;
case 'simple':
return (is('string', value, options) ||
is('number', value, options) ||
is('boolean', value, options) ||
is('undefined', value, options) ||
is('null', value, options));
case 'not-array-object':
return !is('array', value, options) && !is('object', value, options);
default:
return false;
}
}
exports.default = is;
}(is$3, is$3.exports));
var is$2 = /*@__PURE__*/getDefaultExportFromCjs(is$3.exports);
var copy$1 = {};
Object.defineProperty(copy$1, "__esModule", { value: true });
const isArray = value => Array.isArray(value);
const isObject = value => typeof value === 'object' && !!value && value.constructor === Object;
// It keeps the references of the methods and classes,
// unlike JSON.stringify usually used for deep simple copy
const copy = (value, values_) => {
const values = !values_ ? new WeakSet() : values_;
// Ref circular value
if (values.has(value))
return value;
if (isObject(value) || isArray(value))
values.add(value);
if (isArray(value))
return value.map(item => copy(item, values));
if (isObject(value)) {
const newValue = {};
Object.keys(value).forEach(key => newValue[key] = copy(value[key], values));
return newValue;
}
return value;
};
var _default$5 = copy$1.default = copy;
var __importDefault$4 = (undefined && undefined.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(merge$1, "__esModule", { value: true });
const is_1$4 = __importDefault$4(is$3.exports);
const copy_1 = __importDefault$4(copy$1);
const optionsDefault$5 = {
copy: false,
merge: {
array: false,
},
};
const merge = (target, source, options_ = {}) => {
const options = Object.assign(Object.assign({}, optionsDefault$5), options_);
if (options.merge.array &&
(0, is_1$4.default)('array', target) && (0, is_1$4.default)('array', source)) {
const length = Math.max(target.length, source.length);
for (let i = 0; i < length; i++) {
if (target[i] === undefined)
target[i] = source[i];
if (((0, is_1$4.default)('object', target[i]) && (0, is_1$4.default)('object', source[i])) ||
(0, is_1$4.default)('array', target[i]) && (0, is_1$4.default)('array', source[i]))
target[i] = merge(target[i], source[i], options);
}
}
if ((0, is_1$4.default)('object', target) && (0, is_1$4.default)('object', source)) {
Object.keys(source).forEach(key => {
// We only care about direct target object properties
// not about inherited properties from a prototype chain
if (target.hasOwnProperty(key)) {
if ((0, is_1$4.default)('object', target[key]) && (0, is_1$4.default)('object', source[key]))
target[key] = merge(target[key], source[key], options);
}
else
target[key] = options.copy ? (0, copy_1.default)(source[key]) : source[key];
});
}
return target;
};
var _default$4 = merge$1.default = merge;
const optionsDefault$4 = {};
const units = ['millisecond', 'milliseconds', 'second', 'minute', 'minutes', 'hour', 'hours', 'day', 'days', 'dayWeek', 'dayYear', 'week', 'weeks', 'month', 'months', 'year'];
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const monthsAbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const daysWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
const daysWeekAbr = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
class OnesyDate {
static get utc() {
return new OnesyDate(new Date(), {
utc: true
});
}
static get daysInMonth() {
return new OnesyDate().daysInMonth;
}
static get valueOf() {
return new OnesyDate().valueOf;
}
static get unix() {
return new OnesyDate().unix;
}
static get milliseconds() {
return new OnesyDate().milliseconds;
}
static get iso() {
return new OnesyDate().iso;
}
static get onesyDate() {
return new OnesyDate();
}
static get local() {
return new OnesyDate().local;
}
constructor() {
let value_ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this.value_ = value_;
this.options = options;
_defineProperty(this, "value", void 0);
_defineProperty(this, "millisecond", void 0);
_defineProperty(this, "milliseconds", void 0);
_defineProperty(this, "second", void 0);
_defineProperty(this, "minute", void 0);
_defineProperty(this, "minutes", void 0);
_defineProperty(this, "hour", void 0);
_defineProperty(this, "hours", void 0);
_defineProperty(this, "day", void 0);
_defineProperty(this, "days", void 0);
_defineProperty(this, "dayWeek", void 0);
_defineProperty(this, "dayYear", void 0);
_defineProperty(this, "week", void 0);
_defineProperty(this, "weeks", void 0);
_defineProperty(this, "month", void 0);
_defineProperty(this, "months", void 0);
_defineProperty(this, "year", void 0);
this.init();
}
init() {
// Merge options with option defaults
this.options = _default$4(this.options, optionsDefault$4); // Make a date object from it
this.value = new Date(this.value_.valid ? this.value_.value : this.value_);
if (this.valid) {
this.millisecond = this.value[this.options.utc ? 'getUTCMilliseconds' : 'getMilliseconds']();
this.milliseconds = this.value.getTime();
this.second = this.value[this.options.utc ? 'getUTCSeconds' : 'getSeconds']();
this.minute = this.value[this.options.utc ? 'getUTCMinutes' : 'getMinutes']();
this.minutes = Math.ceil(this.milliseconds / (1e3 * 60));
this.hour = this.value[this.options.utc ? 'getUTCHours' : 'getHours']();
this.hours = Math.ceil(this.milliseconds / (1e3 * 60 * 60));
this.day = this.value[this.options.utc ? 'getUTCDate' : 'getDate']();
this.days = Math.ceil(this.milliseconds / (1e3 * 60 * 60 * 24));
this.dayWeek = this.value[this.options.utc ? 'getUTCDay' : 'getDay'](); // https://stackoverflow.com/a/64293860 ty
this.weeks = Math.ceil((this.milliseconds / 1000 + 345600) / 604800);
this.month = this.value[this.options.utc ? 'getUTCMonth' : 'getMonth']() + 1;
this.year = this.value[this.options.utc ? 'getUTCFullYear' : 'getFullYear']();
this.dayYear = Math.ceil((this.milliseconds - Number(new Date(this.year, 0, 0))) / 1000 / 60 / 60 / 24);
this.months = (this.year - 1970) * 12 - (12 - this.month);
this.weekValue();
}
}
weekValue() {
const WEEK_MILLISECONDS = 604800000;
const firstDayOfWeek = 1;
const startOfYear = new Date(this.year, 0, 1);
startOfYear.setDate(startOfYear.getDate() + (firstDayOfWeek - startOfYear.getDay() % 7));
this.week = Math.round((Number(this.value) - Number(startOfYear)) / WEEK_MILLISECONDS) + 1;
return this.week;
}
get monthsNames() {
var _this$options$overrid;
return ((_this$options$overrid = this.options.overrides) === null || _this$options$overrid === void 0 ? void 0 : _this$options$overrid.months) || months;
}
get monthsAbr() {
var _this$options$overrid2;
return ((_this$options$overrid2 = this.options.overrides) === null || _this$options$overrid2 === void 0 ? void 0 : _this$options$overrid2.monthsAbr) || monthsAbr;
}
get daysWeek() {
var _this$options$overrid3;
return ((_this$options$overrid3 = this.options.overrides) === null || _this$options$overrid3 === void 0 ? void 0 : _this$options$overrid3.daysWeek) || daysWeek;
}
get daysWeekAbr() {
var _this$options$overrid4;
return ((_this$options$overrid4 = this.options.overrides) === null || _this$options$overrid4 === void 0 ? void 0 : _this$options$overrid4.daysWeekAbr) || daysWeekAbr;
}
get valid() {
var _this$value;
return (this.value_ === undefined || this.value_ instanceof Date || this.value_ instanceof OnesyDate || typeof this.value_ === 'number') && !Number.isNaN(Math.ceil(((_this$value = this.value) === null || _this$value === void 0 ? void 0 : _this$value.getTime()) / 1000));
}
get local() {
if (this.valid) return new OnesyDate(new Date(this.value.toLocaleString('en-us')));
}
get utc() {
return new OnesyDate(this.value, {
utc: true
});
}
get iso() {
if (this.valid) return this.value.toISOString();
}
get daysInMonth() {
return new Date(this.year, this.month, 0).getDate();
}
get weeksInYear() {
const date = new Date(this.year, 0, 1);
const isLeapYear = new Date(this.year, 1, 29).getMonth() === 1;
return date.getDay() === 4 || isLeapYear && date.getDay() === 3 ? 53 : 52;
}
get valueOf() {
return this.milliseconds;
}
get unix() {
if (this.valid) return Math.floor(this.value.getTime() / 1000);
}
timezone(value) {
if (this.valid && value) return new OnesyDate(this.value.toLocaleString('en-us', {
timeZone: value
}));
}
}
const optionsDefault$3 = {};
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
const isNodejs = !!(typeof global$1 !== 'undefined' && typeof module !== 'undefined' && module.exports); // Multiple is methods instead of one,
// so it's lighter for tree shaking usability reasons
function is$1(type, value) {
var _value$constructor;
let options_ = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const options = { ...optionsDefault$3,
...options_
};
const {
variant
} = options;
const prototype = value && typeof value === 'object' && Object.getPrototypeOf(value);
switch (type) {
case 'string':
return typeof value === 'string';
case 'number':
return typeof value === 'number' && !Number.isNaN(value);
case 'boolean':
return typeof value === 'boolean';
case 'array':
return Array.isArray(value);
case 'object':
const isObject = typeof value === 'object' && !!value && value.constructor === Object;
return isObject;
// Map, null, WeakMap, Date, etc.
case 'object-like':
return typeof value === 'object' && (value === null || value.constructor !== Object);
case 'class':
return (typeof value === 'object' || typeof value === 'function') && (/class/gi.test(String(value)) || /class/gi.test(String(value === null || value === void 0 ? void 0 : value.constructor)));
case 'function':
return !!(value && value instanceof Function);
case 'async':
// If it's browser avoid calling the method
// to see if it's async func or not,
// where as in nodejs we have no other choice
// that i know of when using transpilation
// And also it might not be always correct, as
// a method that returns a promise is also async
// but we can't know that until the method is called and
// we inspect the method's return value
return !!(is$1('function', value) && (isBrowser ? value.constructor.name === 'AsyncFunction' : value() instanceof Promise));
case 'map':
return !!(prototype === Map.prototype);
case 'weakmap':
return !!(prototype === WeakMap.prototype);
case 'set':
return !!(prototype === Set.prototype);
case 'weakset':
return !!(prototype === WeakSet.prototype);
case 'promise':
return !!(prototype === Promise.prototype);
case 'int8array':
return !!(prototype === Int8Array.prototype);
case 'uint8array':
return !!(prototype === Uint8Array.prototype);
case 'uint8clampedarray':
return !!(prototype === Uint8ClampedArray.prototype);
case 'int16array':
return !!(prototype === Int16Array.prototype);
case 'uint16array':
return !!(prototype === Uint16Array.prototype);
case 'int32array':
return !!(prototype === Int32Array.prototype);
case 'uint32array':
return !!(prototype === Uint32Array.prototype);
case 'float32array':
return !!(prototype === Float32Array.prototype);
case 'float64array':
return !!(prototype === Float64Array.prototype);
case 'bigint64array':
return !!(prototype === BigInt64Array.prototype);
case 'biguint64array':
return !!(prototype === BigUint64Array.prototype);
case 'typedarray':
return is$1('int8array', value) || is$1('uint8array', value) || is$1('uint8clampedarray', value) || is$1('int16array', value) || is$1('uint16array', value) || is$1('int32array', value) || is$1('uint32array', value) || is$1('float32array', value) || is$1('float64array', value) || is$1('bigint64array', value) || is$1('biguint64array', value);
case 'dataview':
return !!(prototype === DataView.prototype);
case 'arraybuffer':
return !!(prototype === ArrayBuffer.prototype);
case 'sharedarraybuffer':
return typeof SharedArrayBuffer !== 'undefined' && !!(prototype === SharedArrayBuffer.prototype);
case 'symbol':
return !!(typeof value === 'symbol');
case 'error':
return !!(value && value instanceof Error);
case 'date':
return !!(value && value instanceof Date);
case 'regexp':
return !!(value && value instanceof RegExp);
case 'arguments':
return !!(value && value.toString() === '[object Arguments]');
case 'null':
return value === null;
case 'undefined':
return value === undefined;
case 'blob':
return isBrowser && value instanceof Blob;
case 'buffer':
return !!(isNodejs && typeof (value === null || value === void 0 ? void 0 : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.isBuffer) === 'function' && value.constructor.isBuffer(value));
case 'element':
if (value) {
switch (variant) {
case undefined:
case 'html':
case 'element':
return isBrowser && (typeof HTMLElement === 'object' ? value instanceof HTMLElement : value && typeof value === 'object' && value !== null && value.nodeType === 1 && typeof value.nodeName === 'string');
case 'node':
return isBrowser && (typeof Node === 'object' ? value instanceof Node : value && typeof value === 'object' && value !== null && typeof value.nodeType === 'number' && typeof value.nodeName === 'string');
case 'react':
return value.elementType || value.hasOwnProperty('$$typeof');
default:
return false;
}
}
return false;
case 'simple':
return is$1('string', value, options) || is$1('number', value, options) || is$1('boolean', value, options) || is$1('undefined', value, options) || is$1('null', value, options);
case 'not-array-object':
return !is$1('array', value, options) && !is$1('object', value, options);
default:
return false;
}
}
const clamp$2 = function (value) {
let min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Number.MIN_SAFE_INTEGER;
let max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Number.MAX_SAFE_INTEGER;
if (is$1('number', value)) {
if (value < min) return min;
if (value > max) return max;
return value;
}
return value;
};
var clamp$3 = clamp$2;
function add$1(value, unit) {
let onesyDate_ = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : OnesyDate.onesyDate;
if (onesyDate_ && onesyDate_.valid) {
const onesyDate = new OnesyDate(onesyDate_);
switch (unit) {
case 'day':
return new OnesyDate(onesyDate.value.setDate(onesyDate.day + value));
}
}
}
function endOf() {
let onesyDate_ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : OnesyDate.onesyDate;
let unit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'day';
if (onesyDate_ && onesyDate_.valid) {
const onesyDate = new OnesyDate(onesyDate_);
switch (unit) {
case 'second':
return new OnesyDate(onesyDate.value.setMilliseconds(999));
case 'minute':
return new OnesyDate(onesyDate.value.setSeconds(59, 999));
case 'hour':
return new OnesyDate(onesyDate.value.setMinutes(59, 59, 999));
case 'day':
return new OnesyDate(onesyDate.value.setHours(23, 59, 59, 999));
case 'week':
return new OnesyDate(endOf(add$1(onesyDate.dayWeek === 0 ? 0 : 7 - onesyDate.dayWeek, 'day', onesyDate), 'day'));
case 'month':
return new OnesyDate(new Date(onesyDate.value.setMonth(onesyDate.month, 0)).setHours(23, 59, 59, 999));
case 'year':
return new OnesyDate(new Date(onesyDate.value.setMonth(12, 0)).setHours(23, 59, 59, 999));
}
}
}
function add(value, unit) {
let onesyDate_ = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : OnesyDate.onesyDate;
if (onesyDate_ && onesyDate_.valid) {
const onesyDate = new OnesyDate(onesyDate_);
switch (unit) {
case 'millisecond':
return new OnesyDate(onesyDate.value.setMilliseconds(onesyDate.millisecond + value));
case 'second':
return new OnesyDate(onesyDate.value.setSeconds(onesyDate.second + value));
case 'minute':
return new OnesyDate(onesyDate.value.setMinutes(onesyDate.minute + value));
case 'hour':
return new OnesyDate(onesyDate.value.setHours(onesyDate.hour + value));
case 'day':
return new OnesyDate(onesyDate.value.setDate(onesyDate.day + value));
case 'week':
return new OnesyDate(onesyDate.value.setDate(onesyDate.day + value * 7));
case 'month':
// Get middle of month to move to
// and its endOf month,
// move to that months actual day or last day
let day = onesyDate.day;
let month = new OnesyDate(onesyDate.value.setDate(15));
month = new OnesyDate(onesyDate.value.setMonth(onesyDate.month - 1 + value));
const monthEnd = endOf(month, 'month');
day = clamp$3(day, 0, monthEnd.day);
month.value.setDate(day);
month = new OnesyDate(month.value);
return month;
case 'year':
return new OnesyDate(onesyDate.value.setFullYear(onesyDate.year + value));
}
}
}
function ago() {
let onesyDate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : OnesyDate.onesyDate;
let withSufix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
const now = new OnesyDate();
if (onesyDate.valid && onesyDate.milliseconds < now.milliseconds) {
let value = '';
const ago_ = {
milliseconds: now.milliseconds - onesyDate.milliseconds
};
ago_['second'] = Math.floor(ago_['milliseconds'] / 1e3);
ago_['minute'] = Math.floor(ago_['second'] / 6e1);
ago_['hour'] = Math.floor(ago_['minute'] / 6e1);
ago_['day'] = Math.floor(ago_['hour'] / 24);
ago_['month'] = Math.floor(ago_['day'] / 30);
ago_['year'] = Math.floor(ago_['month'] / 12);
units.forEach(unit => {
if (ago_[unit] > 0) value = ago_[unit] === 1 ? "a".concat(unit === 'hour' ? 'n' : '', " ").concat(unit) : "".concat(ago_[unit], " ").concat(unit, "s");
if (unit === 'second' && ago_[unit] < 14) value = "a few seconds";
});
return "".concat(value).concat(withSufix ? ' ago' : '');
}
}
function diff(value, value1) {
let unit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'millisecond';
if (value && value.valid && value1 && value1.valid) {
const diffs = {};
units.forEach(unit_ => diffs[unit_] = Math.floor(value[unit_] - value1[unit_]));
return Math.abs(diffs[unit]);
}
}
var clamp$1 = {};
var __importDefault$3 = (undefined && undefined.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(clamp$1, "__esModule", { value: true });
const is_1$3 = __importDefault$3(is$3.exports);
const clamp = (value, min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER) => {
if ((0, is_1$3.default)('number', value)) {
if (value < min)
return min;
if (value > max)
return max;
return value;
}
return value;
};
var _default$3 = clamp$1.default = clamp;
function duration(value) {
let unitAbbr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
let raw = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
let separator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ' ';
let display = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
let options = arguments.length > 5 ? arguments[5] : undefined;
const l = (options === null || options === void 0 ? void 0 : options.l) || (value => value);
if (is$2('number', value)) {
let result = '';
let milliseconds = value;
const values = [];
const valuesRaw = {};
const millisecondsInTime = {
millisecond: 1,
second: 1e3,
minute: 60 * 1e3,
hour: 60 * 60 * 1e3,
day: 24 * 60 * 60 * 1e3,
month: 30 * 24 * 60 * 60 * 1e3,
year: 12 * 30 * 24 * 60 * 60 * 1e3
};
const unitsAbbr = {
millisecond: 'ms',
second: 's',
minute: 'm',
hour: 'h',
day: 'd',
month: 'mo',
year: 'y'
};
for (const unit of display) {
if (millisecondsInTime[unit]) {
const value_ = _default$3(Math.floor(milliseconds / millisecondsInTime[unit]), 0);
if (value_ > 0) {
milliseconds -= value_ * millisecondsInTime[unit];
valuesRaw[unit] = value_;
let valueTime = value_;
if (unitAbbr) valueTime = "".concat(valueTime, " ").concat(l(unitsAbbr[unit]));else valueTime = "".concat(valueTime, " ").concat(l("".concat(unit).concat(value_ > 1 ? 's' : '')));
values.push(valueTime);
}
}
}
values.forEach(value_ => result += "".concat(separator).concat(value_));
return raw ? valuesRaw : result.trim();
}
}
var getStringVariables$1 = {};
var __importDefault$2 = (undefined && undefined.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(getStringVariables$1, "__esModule", { value: true });
const is_1$2 = __importDefault$2(is$3.exports);
const optionsDefault$2 = {
variablesRegExp: /(\{.*?\}|\[.*?\])/g,
cleanVariables: true,
placeholderPrefix: '_',
};
const getStringVariables = (value, options_ = {}) => {
const options = Object.assign(Object.assign({}, optionsDefault$2), options_);
let valueWithPlaceholders = value;
if ((0, is_1$2.default)('string', value)) {
let variables = value.match(options.variablesRegExp) || [];
variables.forEach((variable, index) => valueWithPlaceholders = valueWithPlaceholders.replace(variable, `${options.placeholderPrefix}${index}`));
if (options.cleanVariables)
variables = variables.map(variable => variable.slice(1, variable.length - 1));
return {
value,
variables,
valueWithPlaceholders,
};
}
};
var _default$2 = getStringVariables$1.default = getStringVariables;
var setStringVariables$1 = {};
var __importDefault$1 = (undefined && undefined.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(setStringVariables$1, "__esModule", { value: true });
const is_1$1 = __importDefault$1(is$3.exports);
const getStringVariables_1 = __importDefault$1(getStringVariables$1);
const optionsDefault$1 = {
getVariables: true,
cleanVariables: true,
placeholderPrefix: '_',
};
const setStringVariables = (value, variablesToValue = [], options_ = {}) => {
const options = Object.assign(Object.assign({}, optionsDefault$1), options_);
if ((0, is_1$1.default)('string', value)) {
let newValue = value;
let stringVariables = { variables: variablesToValue.map(variable => variable.key) };
if (options.getVariables) {
stringVariables = (0, getStringVariables_1.default)(value, {
cleanVariables: options.cleanVariables,
placeholderPrefix: options.placeholderPrefix,
});
newValue = stringVariables.valueWithPlaceholders;
}
stringVariables.variables.forEach((variable, index) => {
const variableItem = variablesToValue.find(item => item.key === variable);
if (variableItem) {
const variableValue = variableItem.value;
if (variableValue !== undefined)
newValue = newValue.replace(new RegExp(`\\${options.placeholderPrefix}${index}`), variableValue);
}
});
return newValue;
}
};
var _default$1 = setStringVariables$1.default = setStringVariables;
var getLeadingZerosNumber$1 = {};
var castParam$1 = {};
var __importDefault = (undefined && undefined.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(castParam$1, "__esModule", { value: true });
const is_1 = __importDefault(is$3.exports);
const optionsDefault = {
decode: false,
decodeMethod: decodeURIComponent,
};
const castParam = (value, options_ = {}) => {
const options = Object.assign(Object.assign({}, optionsDefault), options_);
let newValue = value;
try {
if ((0, is_1.default)('string', value) &&
options.decode &&
(0, is_1.default)('function', options.decodeMethod))
newValue = options.decodeMethod(value);
}
catch (error) { }
try {
if ((0, is_1.default)('string', newValue)) {
if ('undefined' === newValue)
return undefined;
if ('NaN' === newValue)
return NaN;
return JSON.parse(newValue);
}
return newValue;
}
catch (error) { }
return newValue;
};
castParam$1.default = castParam;
(function (exports) {
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLeadingZerosNumber = void 0;
const is_1 = __importDefault(is$3.exports);
const castParam_1 = __importDefault(castParam$1);
const optionsDefault = {
leadingZeros: 1,
};
const getLeadingZerosNumber = (value_, options_ = {}) => {
const options = Object.assign(Object.assign({}, optionsDefault), options_);
const value = (0, castParam_1.default)(value_);
if ((0, is_1.default)('number', value) && value >= 0) {
let leadingZeros = '';
const string = String(value);
const leadingZerosToAdd = (options.leadingZeros + 1) - string.length;
if (leadingZerosToAdd > 0)
for (const _ of new Array(leadingZerosToAdd))
leadingZeros += '0';
return `${leadingZeros}${string}`;
}
return String(value_);
};
exports.getLeadingZerosNumber = getLeadingZerosNumber;
exports.default = exports.getLeadingZerosNumber;
}(getLeadingZerosNumber$1));
var getLeadingZerosNumber = /*@__PURE__*/getDefaultExportFromCjs(getLeadingZerosNumber$1);
var getOrdinalNumber$1 = {};
(function (exports) {
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOrdinalNumber = void 0;
const is_1 = __importDefault(is$3.exports);
const castParam_1 = __importDefault(castParam$1);
const optionsDefault = {
onlySufix: false,
};
const getOrdinalNumber = (value_, options_ = {}) => {
const options = Object.assign(Object.assign({}, optionsDefault), options_);
const value = (0, castParam_1.default)(value_);
if ((0, is_1.default)('number', value)) {
let sufix = 'th';
const string = String(value);
if (value === 1 || (value > 20 && string[string.length - 1] === '1'))
sufix = 'st';
else if (value === 2 || (value > 20 && string[string.length - 1] === '2'))
sufix = 'nd';
else if (value === 3 || (value > 20 && string[string.length - 1] === '3'))
sufix = 'rd';
if (options.onlySufix)
return sufix;
return `${value}${sufix}`;
}
};
exports.getOrdinalNumber = getOrdinalNumber;
exports.default = exports.getOrdinalNumber;
}(getOrdinalNumber$1));
var getOrdinalNumber = /*@__PURE__*/getDefaultExportFromCjs(getOrdinalNumber$1);
function getTimezoneOffset() {
let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new OnesyDate();
let divider = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ':';
if (value && value.valid) {
const timezoneOffset = value.value.getTimezoneOffset();
const sign = timezoneOffset < 0 ? '+' : '-';
const difference = Math.abs(timezoneOffset) / 60;
const items = String(difference).split('.').filter(Boolean);
const hours = getLeadingZerosNumber(parseInt(items[0], 10));
const minutes = items[1] && parseInt(items[1], 10) * 10;
return "".concat(sign).concat(hours).concat(divider).concat(minutes ? minutes : '00');
}
}
function myTimezoneAbbr() {
let timezoneAbr = new Date().toLocaleTimeString('en-us', {
timeZoneName: 'short'
});
if (timezoneAbr) timezoneAbr = timezoneAbr.split(' ')[2];
return timezoneAbr;
}
function formats() {
let onesyDate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : OnesyDate.onesyDate;
const timezoneAbbr = myTimezoneAbbr();
return [// Milliseconds
{
abr: 'SSSS',
value: getLeadingZerosNumber(onesyDate.millisecond, {
leadingZeros: 3
}).slice(0, 4)
}, {
abr: 'SSS',
value: getLeadingZerosNumber(onesyDate.millisecond, {
leadingZeros: 2
}).slice(0, 3)
}, {
abr: 'SS',
value: getLeadingZerosNumber(onesyDate.millisecond, {
leadingZeros: 1
}).slice(0, 2)
}, {
abr: 'S',
value: getLeadingZerosNumber(onesyDate.millisecond, {
leadingZeros: 0
}).slice(0, 1)
}, // Seconds
{
abr: 'ss',
value: getLeadingZerosNumber(onesyDate.second)
}, {
abr: 's',
value: String(onesyDate.second)
}, // Minutes
{
abr: 'mm',
value: getLeadingZerosNumber(onesyDate.minute)
}, {
abr: 'm',
value: String(onesyDate.minute)
}, // Hours
{
abr: 'HH',
value: getLeadingZerosNumber(onesyDate.hour)
}, {
abr: 'H',
value: String(onesyDate.hour)
}, {
abr: 'hh',
value: getLeadingZerosNumber(onesyDate.hour > 12 ? onesyDate.hour - 12 : onesyDate.hour)
}, {
abr: 'h',
value: String(onesyDate.hour > 12 ? onesyDate.hour - 12 : onesyDate.hour)
}, // Day
{
abr: 'Do',
value: getOrdinalNumber(onesyDate.day)
}, {
abr: 'DD',
value: getLeadingZerosNumber(onesyDate.day)
}, {
abr: 'D',
value: String(onesyDate.day)
}, {
abr: 'dd',
value: onesyDate.daysWeek[onesyDate.dayWeek - 1 < 0 ? onesyDate.daysWeek.length - 1 : onesyDate.dayWeek - 1]
}, {
abr: 'd',
value: onesyDate.daysWeekAbr[onesyDate.dayWeek - 1 < 0 ? onesyDate.daysWeekAbr.length - 1 : onesyDate.dayWeek - 1]
}, // Month
{
abr: 'Mo',
value: getOrdinalNumber(onesyDate.month)
}, {
abr: 'MMMM',
value: onesyDate.monthsNames[onesyDate.month - 1 < 0 ? onesyDate.monthsNames.length - 1 : onesyDate.month - 1]
}, {
abr: 'MMM',
value: onesyDate.monthsAbr[onesyDate.month - 1 < 0 ? onesyDate.monthsAbr.length - 1 : onesyDate.month - 1]
}, {
abr: 'MM',
value: getLeadingZerosNumber(onesyDate.month)
}, {
abr: 'M',
value: String(onesyDate.month)
}, // Year
{
abr: 'YYYY',
value: String(onesyDate.year)
}, // AM / PM
{
abr: 'A',
value: onesyDate.hour < 12 ? 'AM' : 'PM'
}, {
abr: 'a',
value: onesyDate.hour < 12 ? 'am' : 'pm'
}, // Timezone offset
{
abr: 'ZZ',
value: getTimezoneOffset(onesyDate, '')
}, {
abr: 'Z',
value: getTimezoneOffset(onesyDate)
}, // Timezone abr
{
abr: 'z',
value: timezoneAbbr
}, // Unix
{
abr: 'X',
value: String(onesyDate.unix)
}, {
abr: 'x',
value: String(onesyDate.value.getTime())
}];
}
function format() {
let onesyDate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : OnesyDate.onesyDate;
let value_ = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "YYYY-MM-DDTHH:mm:ss";
let options = arguments.length > 2 ? arguments[2] : undefined;
const l = (options === null || options === void 0 ? void 0 : options.l) || (value => value);
if (onesyDate && onesyDate.valid) {
let value = value_;
const formatValues = formats(onesyDate);
const abrs = formatValues.map(item => item.abr); // Extract and save all words quoted with: '', "", ``, {} or [],
// in a string, so adding abr values doesn't override 'em
const words = _default$2(value, {
variablesRegExp: /('.*?'|".*?"|`.*?`|\{.*?\}|\[.*?\])/g
}); // Add placeholders before adding all abr values
value = words.valueWithPlaceholders; // Replace all abr values
// tslint:disable-next-line
const reAbr = abrs.reduce((result, current, index) => result += "".concat(current).concat(index !== abrs.length - 1 ? '|' : ''), '');
const abrVariables = _default$2(value, {
variablesRegExp: new RegExp(reAbr, 'g'),
cleanVariables: false,
placeholderPrefix: '__'
}); // Add placeholders for matches prior to adding all abr values
value = abrVariables.valueWithPlaceholders;
const abrVariablesToValue = [];
abrVariables.variables.forEach(variable => {
const format_ = formatValues.find(item => item.abr === variable);
abrVariablesToValue.push({
key: variable,
value: l(format_.value)
});
}); // Replace abr variables with appropriate values
value = _default$1(value, abrVariablesToValue, {
getVariables: false,
placeholderPrefix: '__'
}); // Revert back all the saved words
const wordsVariablesToValue = [];
words.variables.forEach(variable => wordsVariablesToValue.push({
key: variable,
value: variable
}));
value = _default$1(value, wordsVariablesToValue, {
getVariables: false
});
return value;
}
}
function remove(value, unit) {
let onesyDate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : OnesyDate.onesyDate;
if (onesyDate && onesyDate.valid) return add(value * -1, unit, onesyDate);
}
function startOf() {
let onesyDate_ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : OnesyDate.onesyDate;
let unit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'day';
if (onesyDate_ && onesyDate_.valid) {
const onesyDate = new OnesyDate(onesyDate_);
switch (unit) {
case 'second':
return new OnesyDate(onesyDate.value.setMilliseconds(0));
case 'minute':
return new OnesyDate(onesyDate.value.setSeconds(0, 0));
case 'hour':
return new OnesyDate(onesyDate.value.setMinutes(0, 0, 0));
case 'day':
return new OnesyDate(onesyDate.value.setHours(0, 0, 0, 0));
case 'week':
return new OnesyDate(startOf(remove((onesyDate.dayWeek === 0 ? 7 : onesyDate.dayWeek) - 1, 'day', onesyDate), 'day'));
case 'month':
return new OnesyDate(new Date(onesyDate.value.setDate(1)).setHours(0, 0, 0, 0));
case 'year':
return new OnesyDate(new Date(onesyDate.value.setMonth(0, 1)).setHours(0, 0, 0, 0));
}
}
}
function is() {
let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : OnesyDate.onesyDate;
let query = arguments.length > 1 ? arguments[1] : undefined;
let value1 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : OnesyDate.onesyDate;
let unit = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'milliseconds';
let value2 = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : OnesyDate.onesyDate;
if (value && value.valid) {
if (value1 && value1.valid) {
const diffs = {};
units.forEach(unit_ => diffs[unit_] = Math.floor(value[unit_] - value1[unit_]));
const queryValue = diffs[unit];
switch (query) {
case 'before':
return queryValue < 0;
case 'after':
return queryValue > 0;
case 'same':
return queryValue === 0;
case 'between':
if (value2 && value2.valid) {
return is(value2, 'after or same', value) && is(value2, 'before or same', value1) || is(value2, 'after or same', value1) && is(value2, 'before or same', value);
}
return false;
case 'before or same':
return queryValue <= 0;
case 'after or same':
return queryValue >= 0;
}
}
switch (query) {
case 'leap-year':
return value.year % 4 === 0 && value.year % 100 !== 0 || value.year % 400 === 0;
case 'leap-month':
return value.month === 2 && value.daysInMonth === 29;
default:
return false;
}
}
}
function In() {
let to = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : OnesyDate.onesyDate;
let withPrefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
let from = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : OnesyDate.onesyDate;
if (to.valid && from.valid && to.milliseconds > from.milliseconds) {
let value = '';
const ins = {
milliseconds: to.milliseconds - from.milliseconds
};
ins['second'] = Math.floor(ins['milliseconds'] / 1e3);
ins['minute'] = Math.floor(ins['second'] / 6e1);
ins['hour'] = Math.floor(ins['minute'] / 6e1);
ins['day'] = Math.floor(ins['hour'] / 24);
ins['month'] = Math.floor(ins['day'] / 30);
ins['year'] = Math.floor(ins['month'] / 12);
units.forEach(unit => {
if (ins[unit] > 0) value = ins[unit] === 1 ? "a".concat(unit === 'hour' ? 'n' : '', " ").concat(unit) : "".concat(ins[unit], " ").concat(unit, "s");
if (unit === 'second' && ins[unit] < 14) value = "a few seconds";else if (unit === 'millisecond' && ins[unit] < 14) value = "a few seconds";
});
return "".concat(withPrefix ? 'in ' : '').concat(value);
}
}
var isExists$1 = {};
Object.defineProperty(isExists$1, "__esModule", { value: true });
function isExists(type) {
switch (type) {
case 'Intl':
return typeof Intl !== 'undefined';
default:
return false;
}
}
var _default = isExists$1.default = isExists;
const timezones = [{
label: 'Pacific/Midway (GMT-11:00)',
code: 'Pacific/Midway',
name: '(GMT-11:00) Midway',
utc: '-11:00',
abbr: 'SST'
}, {
label: 'Pacific/Niue (GMT-11:00)',
code: 'Pacific/Niue',
name: '(GMT-11:00) Alofi',
utc: '-11:00',
abbr: '-11'
}, {
label: 'Pacific/Pago_Pago (GMT-11:00)',
code: 'Pacific/Pago_Pago',
name: '(GMT-11:00) Pago Pago, Tāfuna, Ta`ū, Taulaga',
utc: '-11:00',
abbr: 'SST'
}, {
label: 'America/Adak (GMT-10:00)',
code: 'America/Adak',
name: '(GMT-10:00) Adak',
utc: '-10:00',
abbr: 'HST'
}, {
label: 'Pacific/Honolulu (GMT-10:00)',
code: 'Pacific/Honolulu',
name: '(GMT-10:00) Honolulu, East Honolulu, Pearl City, Hilo, Kailua',
utc: '-10:00',
abbr: 'HST'
}, {
label: 'Pacific/Rarotonga (GMT-10:00)',
code: 'Pacific/Rarotonga',
name: '(GMT-10:00) Avarua',
utc: '-10:00',
abbr: '-10'
}, {
label: 'Pacific/Tahiti (GMT-10:00)',
code: 'Pacific/Tahiti',
name: '(GMT-10:00) Faaa, Papeete, Punaauia, Pirae, Mahina',
utc: '-10:00',
abbr: '-10'
}, {
label: 'Pacific/Marquesas (GMT-09:30)',