/**
* Time utility functions for ISO 8601 timestamp handling
*/
/**
* Validates and normalizes ISO 8601 timestamp
* @param timestamp - ISO 8601 timestamp string
* @returns Validated timestamp or throws error
*/
export function validateTimestamp(timestamp: string): string {
const date = new Date(timestamp);
if (isNaN(date.getTime())) {
throw new Error(`Invalid ISO 8601 timestamp: ${timestamp}`);
}
return date.toISOString();
}
/**
* Validates time range (from must be before to)
* @param from - Start timestamp
* @param to - End timestamp
*/
export function validateTimeRange(from: string, to: string): void {
const fromDate = new Date(from);
const toDate = new Date(to);
if (isNaN(fromDate.getTime()) || isNaN(toDate.getTime())) {
throw new Error('Invalid timestamp in time range');
}
if (fromDate > toDate) {
throw new Error('Time range invalid: "from" must be before "to"');
}
}
/**
* Formats date to ISO 8601 string
* @param date - Date object
* @returns ISO 8601 string
*/
export function toISOString(date: Date): string {
return date.toISOString();
}
/**
* Gets default time range (last 3 months)
* @returns Object with from and to timestamps (ISO 8601 format)
*/
export function getDefaultTimeRange(): { from: string; to: string } {
const to = new Date();
const from = new Date();
from.setMonth(from.getMonth() - 3);
return {
from: from.toISOString(),
to: to.toISOString(),
};
}