datemapper
Version:
A lightweight date utility for format conversion, validation, and date manipulation.
29 lines • 1.58 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const moment = require("moment-timezone"); // Import moment-timezone to handle date-time operations with timezones
/**
* Increments a date by a specified time unit (day, month, hour, year, or week).
* Ensures proper timezone adjustments while maintaining consistency in date calculations.
*
* @param date - The initial Date object to be incremented.
* @param incrementType - The unit of time to increment.
* Accepts one of the following values: "day", "month", "hour", "year", "week".
* @param timezone - The timezone in which the date should be interpreted and adjusted.
* @returns A new Date object representing the incremented date.
* @throws {Error} If an invalid increment type is provided.
*/
const incrementDate = (date, incrementType, timezone) => {
// Create a moment object with the specified date and apply the given timezone
const momentDate = moment.tz(date, timezone);
// Validate that incrementType is one of the allowed values
const validTypes = ["day", "month", "hour", "year", "week"];
if (!validTypes.includes(incrementType)) {
throw new Error(`Invalid increment type: ${incrementType}. Allowed values are: ${validTypes.join(", ")}`);
}
// Increment based on the specified unit type
momentDate.add(1, incrementType);
// Normalize the date to the start of the incremented unit
return momentDate.startOf(incrementType).toDate();
};
exports.default = incrementDate;
//# sourceMappingURL=increment-date.js.map