datemapper
Version:
A lightweight date utility for format conversion, validation, and date manipulation.
37 lines (30 loc) • 1.66 kB
text/typescript
import * as moment from "moment-timezone"; // Import moment-timezone for handling timezones
import { TIncrementType } from "./types"; // Import type definitions for valid increment types
/**
* Decrements a given 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 that will be decremented.
* @param incrementType - The unit of time by which the date should be decremented.
* 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 decremented date.
* @throws {Error} If an invalid increment type is provided.
*/
const decrementDate = (date: Date, incrementType: TIncrementType, timezone: string): Date => {
// Create a moment object with the specified date and apply the given timezone.
const momentDate = moment.tz(date, timezone);
// Define allowed decrement types
const validTypes: TIncrementType[] = ["day", "month", "hour", "year", "week"];
// Validate that incrementType is one of the allowed values
if (!validTypes.includes(incrementType)) {
throw new Error(
`Invalid increment type: ${incrementType}. Allowed values are: ${validTypes.join(", ")}`
);
}
// Subtract the specified time unit dynamically
momentDate.subtract(1, incrementType);
// Normalize the date to the start of the decremented unit
return momentDate.startOf(incrementType).toDate();
};
export default decrementDate;