@qntm-code/utils
Version:
A collection of useful utility functions with associated TypeScript types. All functions have been unit tested.
78 lines (77 loc) • 2.55 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.modifyDate = void 0;
const index_js_1 = require("../convert-units/index.js");
const index_js_2 = require("../getters/index.js");
/**
* Modifies a date by a given amount of time units
*/
function modifyDate(date, amount, unit) {
let newDate = new Date(date);
amount = Math.round(amount);
const originalHour = date.getHours();
switch (unit) {
case index_js_1.TimeUnit.Millisecond:
case index_js_1.TimeUnit.Milliseconds:
case index_js_1.TimeUnit.Second:
case index_js_1.TimeUnit.Seconds:
case index_js_1.TimeUnit.Minute:
case index_js_1.TimeUnit.Minutes:
case index_js_1.TimeUnit.Hour:
case index_js_1.TimeUnit.Hours: {
newDate = new Date(newDate.getTime() + (0, index_js_1.unitToMS)(amount, unit));
break;
}
case index_js_1.TimeUnit.Day:
case index_js_1.TimeUnit.Days: {
newDate.setDate(newDate.getDate() + amount);
break;
}
case index_js_1.TimeUnit.Week:
case index_js_1.TimeUnit.Weeks: {
newDate.setDate(newDate.getDate() + amount * 7);
break;
}
case index_js_1.TimeUnit.Month:
case index_js_1.TimeUnit.Months:
case index_js_1.TimeUnit.Year:
case index_js_1.TimeUnit.Years: {
newDate = (0, index_js_2.getStartOfMonth)(newDate);
break;
}
}
switch (unit) {
case index_js_1.TimeUnit.Month:
case index_js_1.TimeUnit.Months: {
newDate.setMonth(newDate.getMonth() + amount);
break;
}
case index_js_1.TimeUnit.Year:
case index_js_1.TimeUnit.Years: {
newDate.setFullYear(newDate.getFullYear() + amount);
break;
}
}
switch (unit) {
case index_js_1.TimeUnit.Month:
case index_js_1.TimeUnit.Months:
case index_js_1.TimeUnit.Year:
case index_js_1.TimeUnit.Years: {
limitLastDayOfMonth(date, newDate);
newDate.setHours(originalHour);
break;
}
}
return newDate;
}
exports.modifyDate = modifyDate;
function limitLastDayOfMonth(date, newDate) {
const currentLastDay = date.getDate();
const newDateLastDay = (0, index_js_2.getEndOfMonth)(newDate).getDate();
if (currentLastDay > newDateLastDay) {
newDate.setDate(newDateLastDay);
}
else {
newDate.setDate(currentLastDay);
}
}