toDate.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. exports.toDate = toDate;
  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. * @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).
  20. *
  21. * @param argument - The value to convert
  22. *
  23. * @returns The parsed date in the local time zone
  24. *
  25. * @example
  26. * // Clone the date:
  27. * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
  28. * //=> Tue Feb 11 2014 11:30:30
  29. *
  30. * @example
  31. * // Convert the timestamp to date:
  32. * const result = toDate(1392098430000)
  33. * //=> Tue Feb 11 2014 11:30:30
  34. */
  35. function toDate(argument) {
  36. const argStr = Object.prototype.toString.call(argument);
  37. // Clone the date
  38. if (
  39. argument instanceof Date ||
  40. (typeof argument === "object" && argStr === "[object Date]")
  41. ) {
  42. // Prevent the date to lose the milliseconds when passed to new Date() in IE10
  43. return new argument.constructor(+argument);
  44. } else if (
  45. typeof argument === "number" ||
  46. argStr === "[object Number]" ||
  47. typeof argument === "string" ||
  48. argStr === "[object String]"
  49. ) {
  50. // TODO: Can we get rid of as?
  51. return new Date(argument);
  52. } else {
  53. // TODO: Can we get rid of as?
  54. return new Date(NaN);
  55. }
  56. }