@xassist/xassist-date
Version:
helper functions for date manipulation
7 lines • 11.1 kB
JavaScript
/**
* @preserve
* https://github.com/GregBee2/xassist-date.git Version 1.2.2.
* Copyright 2018 Gregory Beirens.
* Created on Tue, 17 Apr 2018 10:42:12 GMT.
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@xassist/xassist-object")):"function"==typeof define&&define.amd?define(["exports","@xassist/xassist-object"],e):e(t.xa=t.xa||{},t.xa)}(this,function(t,e){"use strict";function a(t){return+((t<0?"-.":".")+t.toString().split(".")[1])||0}var i=[{key:"year",re:/(-?\d*(?:[.,]\d*)?)(?:[ ]?y|Y|years?|Years?)(?![a-zA-z])/g},{key:"month",re:/(-?\d*(?:[.,]\d*)?)(?:[ ]?M|months?|Months?)(?![a-zA-z])/g},{key:"day",re:/(-?\d*(?:[.,]\d*)?)(?:[ ]?d|D|days?|Days?)(?![a-zA-z])/g},{key:"hour",re:/(-?\d*(?:[.,]\d*)?)(?:[ ]?h|H|hours?|Hours?)(?![a-zA-z])/g},{key:"minute",re:/(-?\d*(?:[.,]\d*)?)(?:[ ]?m|mins?|Mins?|minutes?|Minutes?)(?![a-zA-z])/g},{key:"second",re:/(-?\d*(?:[.,]\d*)?)(?:[ ]?s|S|secs?|Secs?|seconds?|Seconds?)(?![a-zA-z])/g},{key:"millisecond",re:/(-?\d*(?:[.,]\d*)?)(?:[ ]?ms|millis?|m[sS]ecs?|m[sS]econds?|milli[sS]ecs?|milli[sS]econds?)(?![a-zA-z])/g}];var d=function(){return new n([].slice.call(arguments))};function n(t){this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,this.millisecond=0,this.normalized=!1,this.init(t)}n.prototype._keyOrder=["year","month","day","hour","minute","second","millisecond"],n.prototype.init=function(t){1===t.length&&("string"==typeof t[0]?function(t,e){for(var n,r=0,o=i.length;r<o;r++)for(;n=i[r].re.exec(e);)t[i[r].key]+=parseFloat((n[1]||"0").replace(",","."))}(this,t[0]):"number"==typeof t[0]?this.millisecond+=t[0]:"object"==typeof t[0]&&e.object(this).mergeUnique(t[0])),1<t.length&&t.forEach(function(t,e){e<this._keyOrder.length&&"number"==typeof t&&(this[this._keyOrder[e]]+=t)},this)};var r={year:{coeff:7/365.2425,exactType:"big"},month:{coeff:7/30.436875,exactType:"big"},week:{coeff:1,exactType:"small"},day:{coeff:7,exactType:"small"},hour:{coeff:168,exactType:"small"},minute:{coeff:10080,exactType:"small"},second:{coeff:604800,exactType:"small"},millisecond:{coeff:6048e5,exactType:"small"}};n.prototype.normalize=function(t){t=void 0===t||!!t,this.normalizeUp(t),this.normalized||(this.normalizeDown(t),this.normalizeUp(!0))},n.prototype.normalizeDown=function(t){var e,n,r,o;t=void 0===t||!!t;for(var i=0,s=this._keyOrder.length;i<s;i++)e=this._keyOrder[i],(r=this._keyOrder[i+1])&&(o=this.getConversionFactor(e,r),t&&!o.exact||(n=a(this[e]),this[e]=this[e]-n,this[r]+=n*o.factor));return this.normalized=0===a(this.month),this},n.prototype.normalizeUp=function(t){var e,n,r,o,i=this._keyOrder.length,s=!0;for(t=void 0===t||!!t;i--;)e=this._keyOrder[i],(n=this._keyOrder[i-1])&&(r=this.getConversionFactor(n,e),t&&!r.exact||(o=this[e],this[e]=o%r.factor,this[n]+=(o-this[e])/r.factor)),i!==this._keyOrder.length-1&&(s=s&&10*this[e]%10/10==0);return this.normalized=s,this},n.prototype.getConversionFactor=function(t,e){if(r.hasOwnProperty(t)&&r.hasOwnProperty(e))return{factor:r[e].coeff/r[t].coeff,exact:r[e].exactType===r[t].exactType};throw new TypeError("Invalid unit conversion type")},n.prototype.valueOf=function(){for(var t,e=0,n=0,r=this._keyOrder.length;n<r;n++)t=this._keyOrder[n],e+=this.getConversionFactor(t,"millisecond").factor*this[t];return e},n.prototype.toString=function(){var t,e=[],n=this.valueOf(),r=d(Math.abs(n));r.normalize(!1);for(var o=0,i=this._keyOrder.length;o<i;o++)0!==r[t=this._keyOrder[o]]&&e.push(r[t]+" "+t+(1<r[t]?"s":""));return n<0&&e.push("ago"),e.join(" ")+"."},n.prototype.format=function(t){var e,n=[],r=this.valueOf(),o=Math.abs(r),i=d(o),s=0,a=1;if(!t)return this.toString();t=1<(t=Math.abs(t))?1:t,i.normalize(!1);for(var h=0,u=this._keyOrder.length;h<u&&t<=a;h++)0!==i[e=this._keyOrder[h]]&&(s+=i[e]*this.getConversionFactor(e,"millisecond").factor,n.push(i[e]+" "+e+(1<i[e]?"s":"")),a=1-s/o);return(s+=1*this.getConversionFactor(e,"millisecond").factor)/o-1<=a&&n.push(n.pop().split(" ").map(function(t,e){return 0==e?+t+1:t}).join(" ")),r<0&&n.push("ago"),n.join(" ")+"."},n.prototype.addDuration=function(t){var e,n,r;for(n=0,r=this._keyOrder.length;n<r;n++)e=this._keyOrder[n],t.hasOwnProperty(e)&&"number"==typeof t[e]&&(this[e]+=t[e]);return this},n.prototype.removeIntervalOfType=function(t,e){return~this._keyOrder.indexOf(t)?(e="number"==typeof e?e:this[t],this[t]-=e,e):0},n.prototype.normalizeMonth=function(t){var e=a(this.month);return this.month=this.month-e,this.day+=t*e,this.normalizeDown()};var s={days:{defaultKey:"long",abbreviation:["S","M","T","W","T","F","S"],short:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],long:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},month:{defaultKey:"long",abbreviation:["J","F","M","A","M","J","J","A","S","O","N","D"],short:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],long:["January","February","March","April","May","June","July","August","September","October","November","December"]}},o=function(t){if(0<(t=void 0===t?(new Date).getFullYear():t)||t<0)return 0==(3&t)&&(t%25!=0||0==(15&t))},c=function(t,e){var n;return 2===(t=void 0===t?(new Date).getMonth()+1:t)?void 0===(n=o(e))?n:n?29:28:[31,28,31,30,31,30,31,31,30,31,30,31][t-1]},h=function(t){return"[object Date]"===Object.prototype.toString.call(t)&&!isNaN(t.getTime())},l=/^(\d{4}|\d{2}|[1-2]?\d{1}|3[0-1])[-/\\.](0?[1-9]|[1-2]\d{1}|3[0-1])[-/\\.](\d{4}|\d{2}|[1-2]?\d{1}|3[0-1])(?:[T ]([0-1]\d|2[0-3]):([0-5]\d)(?::([0-5]\d)(?:[.,](\d*)?)?)?)?$/i,u=function(t,e,n){var r,o=0;return this&&this.constructor&&"XaDate"===this.constructor.name&&(o=1),r=o?this.getDay():t||0,t=(""+arguments[1-o]||s.days.defaultKey).toLowerCase(),e=o?0:n||0,r=(r-((n=!!o||!(void 0!==arguments[3]&&!arguments[3]))?0:1)+e)%7,t=s.days.hasOwnProperty(t)?t:s.days.defaultKey,r=r<0?7+r:r,s.days[t][r]},y=function(t,e){var n,r=0;return this&&this.constructor&&"XaDate"===this.constructor.name&&(r=1),n=r?this.getMonth():t||0,t=(""+arguments[1-r]||s.month.defaultKey).toLowerCase(),t=s.month.hasOwnProperty(t)?t:s.month.defaultKey,n=(n=(n-(!!r||!(void 0!==arguments[2]&&!arguments[2])?0:1))%12)<0?12+n:n,s.month[t][n]},f=function(){return new p([].slice.call(arguments))};function p(t){var e=new(Function.prototype.bind.apply(Date,[Date].concat(t)));return Object.setPrototypeOf(e,p.prototype),e}f.isValidDateString=function(t){var e,n,r,o,i,s={valid:!1,format:[]},a=t.match(l),h=[];if(a){e=parseInt(a[1]),r=parseInt(a[2]),n=parseInt(a[3]),s.hours=parseInt(a[4]||0),s.minutes=parseInt(a[5]||0),s.seconds=a[6]?parseInt(a[6]):0,s.milliSeconds=a[7]?parseInt(a[7]):0,s.valid=!0,s.multipleFormats=!1;var u=function(t){return t<100?50<t?1900+t:2e3+t:t};return o=u(e),!!(h=[{day:e,month:r,year:i=u(n),format:"DMY"},{day:n,month:r,year:o,format:"YMD"},{day:r,month:e,year:i,format:"MDY"},{day:r,month:n,year:o,format:"YDM"}].filter(function(t){return t.day<32&&t.month<13&&(e=t.day,n=t.month,r=t.year,e<=c(n,r));var e,n,r})).length&&(s.day=[],s.month=[],s.year=[],s.multipleFormats=!0,s.format=[],h.forEach(function(t){s.day.push(t.day),s.month.push(t.month),s.year.push(t.year),s.format.push(t.format)}),s)}return!1},f.stringToDate=function(t,e){var n=f.isValidDateString(t);if(n){if("string"!=typeof e)e=0;else if(-1===(e=n.format.indexOf(e.toUpperCase())))return!1;return f(n.year[e],n.month[e]-1,n.day[e],n.hours,n.minutes,n.seconds,n.milliSeconds)}return!1},Object.setPrototypeOf(p.prototype,Date.prototype),p.prototype.isValid=function(){return h(this)},f.getWeekDay=u.bind(null),f.month=y.bind(null),p.prototype.getWeekDay=u,p.prototype.month=y,p.prototype.isLeapYear=function(){return this.isValid()?o(this.getFullYear()):void 0},f.isLeapYear=o,p.prototype.daysInMonth=function(){return this.isValid()?c(this.getMonth()+1,this.getFullYear()):void 0},f.daysInMonth=c,p.prototype._addSmall=function(t){return this.addDays(t.removeIntervalOfType("day")),this.addHours(t.removeIntervalOfType("hour")),this.addMinutes(t.removeIntervalOfType("minute")),this.addSeconds(t.removeIntervalOfType("second")),this.addMilliseconds(t.removeIntervalOfType("millisecond")),this},p.prototype._addBig=function(t){var e,n=this.getDate(),r=10*t.month%10/10,o=t.month-r;this.addYears(t.removeIntervalOfType("year")),this.addMonths(t.removeIntervalOfType("month",o)),t.month=r,e=this.getMonth(),this.setDate(n),this.getMonth()!==e&&this.setDate(0)},p.prototype.format=function(t){var s={month:[function(t){return(t.getMonth()+1).toString()},function(t){return("0"+(t.getMonth()+1)).slice(-2)},function(t){return t.month("short")},function(t){return t.month("long")},function(t){return t.month("abbreviation")}],day:[function(t){return t.getDate().toString()},function(t){return("0"+t.getDate()).slice(-2)},function(t){return t.getWeekDay("short")},function(t){return t.getWeekDay("long")},function(t){return t.getWeekDay("abbreviation")}],year:[function(t){return t.getFullYear().toString().slice(-2)},function(t){return t.getFullYear().toString()}],time:[function(t,e){return t[e]().toString()},function(t,e){return("0"+t[e]()).slice(-2)}],millisecond:[function(t,e){return t.getMilliseconds().toString().slice(0,e)}]},a=this;return("1"+t).replace(/[\s\S]([dD]+|M[Mm]?|[Mm]{3,}|[yY]+|[hH]+|m{1,2}|[sS]+|[,.]0+)/g,function(t){var e,n,r,o=t[0],i=t.slice(1);return"^"===o?i:o+(n=(e=i)[0],r=e.length,"M"===n||"m"===n&&2<r?s.month[Math.min(r,5)-1](a):"d"===n||"D"===n?s.day[Math.min(r,5)-1](a):"y"===n||"Y"===n?s.year[(2<r)+0](a):"m"===n&&r<3?s.time[r-1](a,"getMinutes"):"s"===n||"S"===n?s.time[Math.min(r,2)-1](a,"getSeconds"):"h"===n||"H"===n?s.time[Math.min(r,2)-1](a,"getHours"):"."===n||","===n?s.millisecond[0](a,r-1):void 0)}).slice(1)},p.prototype.until=function(t){if(h(t)||(t=new p([].slice.call(arguments))),!t.isValid())throw new TypeError("until() needs a date or parseable dateargumenrs");return d(t.valueOf()-this.valueOf())},p.prototype.add=function(t){var e=[].slice.call(arguments),n=e.pop();return"boolean"!=typeof n&&(e.push(n),n=!0),"XaDuration"!==t.constructor.name&&(t=d.apply(null,e)),t.normalizeDown(),n&&(this._addBig(t),t.normalizeMonth(this.daysInMonth())),this._addSmall(t),n||(t.normalizeMonth(this.daysInMonth()),this._addSmall(t),this._addBig(t)),this},p.prototype.addMonths=function(t){var e,n;return"number"!=typeof t||(e=this.getDate(),this.setMonth(this.getMonth()+t,1),n=this.getMonth(),this.setDate(e),this.getMonth()!==n&&this.setDate(0)),this},p.prototype.addYears=function(t){var e;return"number"!=typeof t||(e=this.getMonth(),this.setFullYear(this.getFullYear()+t,e),this.getMonth()!==e&&this.setDate(0)),this},p.prototype.addDays=function(t){return"number"!=typeof t||this.setDate(this.getDate()+t),this},p.prototype.addHours=function(t){return"number"!=typeof t||this.setHours(this.getHours()+t),this},p.prototype.addMinutes=function(t){return"number"!=typeof t||this.setMinutes(this.getMinutes()+t),this},p.prototype.addSeconds=function(t){return"number"!=typeof t||this.setSeconds(this.getSeconds()+t),this},p.prototype.addMilliseconds=function(t){return"number"!=typeof t||this.setMilliseconds(this.getMilliseconds()+t),this},t.date=f,Object.defineProperty(t,"__esModule",{value:!0})});