index.js 1.9 KB

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