index.js 2.1 KB

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