index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import toInteger from "../_lib/toInteger/index.js";
  2. import toDate from "../toDate/index.js";
  3. import setMonth from "../setMonth/index.js";
  4. import requiredArgs from "../_lib/requiredArgs/index.js";
  5. /**
  6. * @name setQuarter
  7. * @category Quarter Helpers
  8. * @summary Set the year quarter to the given date.
  9. *
  10. * @description
  11. * Set the year quarter to the given date.
  12. *
  13. * ### v2.0.0 breaking changes:
  14. *
  15. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  16. *
  17. * @param {Date|Number} date - the date to be changed
  18. * @param {Number} quarter - the quarter of the new date
  19. * @returns {Date} the new date with the quarter set
  20. * @throws {TypeError} 2 arguments required
  21. *
  22. * @example
  23. * // Set the 2nd quarter to 2 July 2014:
  24. * const result = setQuarter(new Date(2014, 6, 2), 2)
  25. * //=> Wed Apr 02 2014 00:00:00
  26. */
  27. export default function setQuarter(dirtyDate, dirtyQuarter) {
  28. requiredArgs(2, arguments);
  29. var date = toDate(dirtyDate);
  30. var quarter = toInteger(dirtyQuarter);
  31. var oldQuarter = Math.floor(date.getMonth() / 3) + 1;
  32. var diff = quarter - oldQuarter;
  33. return setMonth(date, date.getMonth() + diff * 3);
  34. }