index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import _typeof from "@babel/runtime/helpers/esm/typeof";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  3. /**
  4. * @name toDate
  5. * @category Common Helpers
  6. * @summary Convert the given argument to an instance of Date.
  7. *
  8. * @description
  9. * Convert the given argument to an instance of Date.
  10. *
  11. * If the argument is an instance of Date, the function returns its clone.
  12. *
  13. * If the argument is a number, it is treated as a timestamp.
  14. *
  15. * If the argument is none of the above, the function returns Invalid Date.
  16. *
  17. * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
  18. *
  19. * @param {Date|Number} argument - the value to convert
  20. * @returns {Date} the parsed date in the local time zone
  21. * @throws {TypeError} 1 argument required
  22. *
  23. * @example
  24. * // Clone the date:
  25. * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
  26. * //=> Tue Feb 11 2014 11:30:30
  27. *
  28. * @example
  29. * // Convert the timestamp to date:
  30. * const result = toDate(1392098430000)
  31. * //=> Tue Feb 11 2014 11:30:30
  32. */
  33. export default function toDate(argument) {
  34. requiredArgs(1, arguments);
  35. var argStr = Object.prototype.toString.call(argument);
  36. // Clone the date
  37. if (argument instanceof Date || _typeof(argument) === 'object' && argStr === '[object Date]') {
  38. // Prevent the date to lose the milliseconds when passed to new Date() in IE10
  39. return new Date(argument.getTime());
  40. } else if (typeof argument === 'number' || argStr === '[object Number]') {
  41. return new Date(argument);
  42. } else {
  43. if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
  44. // eslint-disable-next-line no-console
  45. console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments");
  46. // eslint-disable-next-line no-console
  47. console.warn(new Error().stack);
  48. }
  49. return new Date(NaN);
  50. }
  51. }