datility
Version:
Missing javascript Date object utilities
2 lines (1 loc) • 2.66 kB
JavaScript
(function(t){typeof define=="function"&&define.amd?define(t):t()})(function(){"use strict";Date.prototype.addDays=function(t){return this.setDate(this.getDate()+t),this},Date.prototype.addWeeks=function(t){return this.setDate(this.getDate()+t*7),this},Date.prototype.addMonths=function(t){return this.setMonth(this.getMonth()+t),this},Date.prototype.addYears=function(t){return this.setFullYear(this.getFullYear()+t),this},Date.prototype.subtractDays=function(t){return this.setDate(this.getDate()-t),this},Date.prototype.subtractWeeks=function(t){return this.setDate(this.getDate()-t*7),this},Date.prototype.subtractMonths=function(t){return this.setMonth(this.getMonth()-t),this},Date.prototype.subtractYears=function(t){return this.setFullYear(this.getFullYear()-t),this},Date.prototype.clone=function(){return new Date(this.getTime())},Date.prototype.isBefore=function(t){return this<t},Date.prototype.isSame=function(t){return this.getTime()===t.getTime()},Date.prototype.isAfter=function(t){return this>t},Date.prototype.isSameOrBefore=function(t){return this<=t},Date.prototype.isSameOrAfter=function(t){return this>=t},Date.prototype.isBetween=function(t,e){return e>=this&&this>=t},Date.prototype.isPast=function(t){if(t)return this<t;const e=new Date;return e.setHours(0,0,0,0),this<e},Date.prototype.isFuture=function(t){const e=this.getHours(),n=new Date(this.getTime());if(n.setHours(0,0,0,0),t)return n>t;const o=new Date;return o.setHours(e),n>o},Date.prototype.isDay=function(t){return this.toLocaleDateString("en-US",{weekday:"long"}).toLocaleLowerCase()===t.toLocaleLowerCase()||this.toLocaleDateString("en-US",{weekday:"short"}).toLocaleLowerCase()===t.toLocaleLowerCase()},Date.prototype.isWorkingDay=function(){return!(this.toLocaleDateString("en-US",{weekday:"long"})==="Saturday"||this.toLocaleDateString("en-US",{weekday:"long"})==="Sunday")},Date.prototype.isWeekend=function(){return this.toLocaleDateString("en-US",{weekday:"long"})==="Saturday"||this.toLocaleDateString("en-US",{weekday:"long"})==="Sunday"},Date.prototype.addWorkingDays=function(t){const e=this.isWeekend();if(isNaN(t))return new Date(NaN);const n=this.getHours(),o=t<0?-1:1,i=Math.floor(t/5);this.setDate(this.getDate()+i*7);let s=Math.abs(t%5);for(;s>0;)this.setDate(this.getDate()+o),this.isWorkingDay()&&(s-=1);return e&&this.isWeekend()&&t!==0&&(this.toLocaleDateString("en-US",{weekday:"long"})==="Saturday"&&this.setDate(this.getDate()+(o<0?2:-1)),this.toLocaleDateString("en-US",{weekday:"long"})==="Sunday"&&this.setDate(this.getDate()+(o<0?1:-2))),this.setHours(n),this},Date.prototype.subtractWorkingDays=function(t){return this.addWorkingDays(-t)}});