aboutsummaryrefslogtreecommitdiff
path: root/src/internal/date.ts
blob: 40751c2d997c6f63017aedcfc258c79ce9b69156 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { FakerError } from '../errors/faker-error';

/**
 * Converts a date passed as a `string`, `number` or `Date` to a valid `Date` object.
 *
 * @param date The date to convert.
 * @param name The reference name used for error messages. Defaults to `'refDate'`.
 *
 * @throws If the given date is invalid.
 */
export function toDate(
  date: string | Date | number,
  name: string = 'refDate'
): Date {
  const converted = new Date(date);

  if (Number.isNaN(converted.valueOf())) {
    throw new FakerError(`Invalid ${name} date: ${date.toString()}`);
  }

  return converted;
}