Typescript Date functions (datehelpers)

Date: 2025-10-21

dateUtils.ts

export function getDateFromInput(n?: any): Date | undefined {
    if (!n) return undefined
    const d = new Date(n);
    if (!d || !Number.isFinite(d?.getTime())) return undefined;
    return d;
}

export function dateToInt(date: Date): number | undefined {
  if (!(date instanceof Date) || isNaN(date.getTime())) {
    return undefined; // Ongeldige datum
  }

  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();

  return year * 10000 + month * 100 + day;
}

export function intToDate(value: number): Date | undefined {
  if (!Number.isInteger(value) || value < 10000101 || value > 99991231) {
    return undefined;
  }

  const year = Math.floor(value / 10000);
  const month = Math.floor((value % 10000) / 100);
  const day = value % 100;

  if (month < 1 || month > 12 || day < 1 || day > 31) {
    return undefined;
  }

  const date = new Date(year, month - 1, day);

  if (
    date.getFullYear() !== year ||
    date.getMonth() + 1 !== month ||
    date.getDate() !== day
  ) {
    return undefined;
  }

  return date;
}
98040cookie-checkTypescript Date functions (datehelpers)