index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = setMonth;
  6. var _index = _interopRequireDefault(require("../_lib/toInteger/index.js"));
  7. var _index2 = _interopRequireDefault(require("../toDate/index.js"));
  8. var _index3 = _interopRequireDefault(require("../getDaysInMonth/index.js"));
  9. var _index4 = _interopRequireDefault(require("../_lib/requiredArgs/index.js"));
  10. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11. /**
  12. * @name setMonth
  13. * @category Month Helpers
  14. * @summary Set the month to the given date.
  15. *
  16. * @description
  17. * Set the month to the given date.
  18. *
  19. * ### v2.0.0 breaking changes:
  20. *
  21. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  22. *
  23. * @param {Date|Number} date - the date to be changed
  24. * @param {Number} month - the month of the new date
  25. * @returns {Date} the new date with the month set
  26. * @throws {TypeError} 2 arguments required
  27. *
  28. * @example
  29. * // Set February to 1 September 2014:
  30. * const result = setMonth(new Date(2014, 8, 1), 1)
  31. * //=> Sat Feb 01 2014 00:00:00
  32. */
  33. function setMonth(dirtyDate, dirtyMonth) {
  34. (0, _index4.default)(2, arguments);
  35. var date = (0, _index2.default)(dirtyDate);
  36. var month = (0, _index.default)(dirtyMonth);
  37. var year = date.getFullYear();
  38. var day = date.getDate();
  39. var dateWithDesiredMonth = new Date(0);
  40. dateWithDesiredMonth.setFullYear(year, month, 15);
  41. dateWithDesiredMonth.setHours(0, 0, 0, 0);
  42. var daysInMonth = (0, _index3.default)(dateWithDesiredMonth); // Set the last day of the new month
  43. // if the original date was the last day of the longer month
  44. date.setMonth(month, Math.min(day, daysInMonth));
  45. return date;
  46. }
  47. module.exports = exports.default;