isValid.mjs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { isDate } from "./isDate.mjs";
  2. import { toDate } from "./toDate.mjs";
  3. /**
  4. * @name isValid
  5. * @category Common Helpers
  6. * @summary Is the given date valid?
  7. *
  8. * @description
  9. * Returns false if argument is Invalid Date and true otherwise.
  10. * Argument is converted to Date using `toDate`. See [toDate](https://date-fns.org/docs/toDate)
  11. * Invalid Date is a Date, whose time value is NaN.
  12. *
  13. * Time value of Date: http://es5.github.io/#x15.9.1.1
  14. *
  15. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  16. *
  17. * @param date - The date to check
  18. *
  19. * @returns The date is valid
  20. *
  21. * @example
  22. * // For the valid date:
  23. * const result = isValid(new Date(2014, 1, 31))
  24. * //=> true
  25. *
  26. * @example
  27. * // For the value, convertable into a date:
  28. * const result = isValid(1393804800000)
  29. * //=> true
  30. *
  31. * @example
  32. * // For the invalid date:
  33. * const result = isValid(new Date(''))
  34. * //=> false
  35. */
  36. export function isValid(date) {
  37. if (!isDate(date) && typeof date !== "number") {
  38. return false;
  39. }
  40. const _date = toDate(date);
  41. return !isNaN(Number(_date));
  42. }
  43. // Fallback for modularized imports:
  44. export default isValid;