index.js 2.3 KB

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