index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import toDate from "../toDate/index.js";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  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]{@link 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. * ### v2.0.0 breaking changes:
  16. *
  17. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  18. *
  19. * - Now `isValid` doesn't throw an exception
  20. * if the first argument is not an instance of Date.
  21. * Instead, argument is converted beforehand using `toDate`.
  22. *
  23. * Examples:
  24. *
  25. * | `isValid` argument | Before v2.0.0 | v2.0.0 onward |
  26. * |---------------------------|---------------|---------------|
  27. * | `new Date()` | `true` | `true` |
  28. * | `new Date('2016-01-01')` | `true` | `true` |
  29. * | `new Date('')` | `false` | `false` |
  30. * | `new Date(1488370835081)` | `true` | `true` |
  31. * | `new Date(NaN)` | `false` | `false` |
  32. * | `'2016-01-01'` | `TypeError` | `false` |
  33. * | `''` | `TypeError` | `false` |
  34. * | `1488370835081` | `TypeError` | `true` |
  35. * | `NaN` | `TypeError` | `false` |
  36. *
  37. * We introduce this change to make *date-fns* consistent with ECMAScript behavior
  38. * that try to coerce arguments to the expected type
  39. * (which is also the case with other *date-fns* functions).
  40. *
  41. * @param {*} date - the date to check
  42. * @returns {Boolean} the date is valid
  43. * @throws {TypeError} 1 argument required
  44. *
  45. * @example
  46. * // For the valid date:
  47. * var result = isValid(new Date(2014, 1, 31))
  48. * //=> true
  49. *
  50. * @example
  51. * // For the value, convertable into a date:
  52. * var result = isValid(1393804800000)
  53. * //=> true
  54. *
  55. * @example
  56. * // For the invalid date:
  57. * var result = isValid(new Date(''))
  58. * //=> false
  59. */
  60. export default function isValid(dirtyDate) {
  61. requiredArgs(1, arguments);
  62. var date = toDate(dirtyDate);
  63. return !isNaN(date);
  64. }