toDate.mjs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * @name toDate
  3. * @category Common Helpers
  4. * @summary Convert the given argument to an instance of Date.
  5. *
  6. * @description
  7. * Convert the given argument to an instance of Date.
  8. *
  9. * If the argument is an instance of Date, the function returns its clone.
  10. *
  11. * If the argument is a number, it is treated as a timestamp.
  12. *
  13. * If the argument is none of the above, the function returns Invalid Date.
  14. *
  15. * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
  16. *
  17. * @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).
  18. *
  19. * @param argument - The value to convert
  20. *
  21. * @returns The parsed date in the local time zone
  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 function toDate(argument) {
  34. const argStr = Object.prototype.toString.call(argument);
  35. // Clone the date
  36. if (
  37. argument instanceof Date ||
  38. (typeof argument === "object" && argStr === "[object Date]")
  39. ) {
  40. // Prevent the date to lose the milliseconds when passed to new Date() in IE10
  41. return new argument.constructor(+argument);
  42. } else if (
  43. typeof argument === "number" ||
  44. argStr === "[object Number]" ||
  45. typeof argument === "string" ||
  46. argStr === "[object String]"
  47. ) {
  48. // TODO: Can we get rid of as?
  49. return new Date(argument);
  50. } else {
  51. // TODO: Can we get rid of as?
  52. return new Date(NaN);
  53. }
  54. }
  55. // Fallback for modularized imports:
  56. export default toDate;