/** * Parses a human-friendly duration string (e.g., '30m', '1h', '2d') into an ISO date string * representing that duration ago from now. * * @param duration - Duration string with format: * Supported units: m (minutes), h (hours), d (days) * @returns ISO date string representing the time that duration ago * @throws Error if the duration format is invalid */ export const parseTimeDuration = (duration: string): string => { const match = /^(\d+)([dhm])$/.exec(duration); if (!match) { throw new Error( 'Invalid time duration format. Expected format: , where unit is m (minutes), h (hours), or d (days). Examples: 30m, 1h, 2d', ); } const value = Number.parseInt(match[1], 10); const unit = match[2]; if (value <= 0) { throw new Error('Time duration value must be greater than 0.'); } let milliseconds: number; switch (unit) { case 'm': milliseconds = value * 60 * 1000; // minutes to ms break; case 'h': milliseconds = value * 60 * 60 * 1000; // hours to ms break; case 'd': milliseconds = value * 24 * 60 * 60 * 1000; // days to ms break; default: throw new Error(`Unsupported time unit: ${unit}`); } const fromDate = new Date(Date.now() - milliseconds); return fromDate.toISOString(); };