setQuarter.mjs 1014 B

1234567891011121314151617181920212223242526272829303132
  1. import { setMonth } from "./setMonth.mjs";
  2. import { toDate } from "./toDate.mjs";
  3. /**
  4. * @name setQuarter
  5. * @category Quarter Helpers
  6. * @summary Set the year quarter to the given date.
  7. *
  8. * @description
  9. * Set the year quarter to the given date.
  10. *
  11. * @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).
  12. *
  13. * @param date - The date to be changed
  14. * @param quarter - The quarter of the new date
  15. *
  16. * @returns The new date with the quarter set
  17. *
  18. * @example
  19. * // Set the 2nd quarter to 2 July 2014:
  20. * const result = setQuarter(new Date(2014, 6, 2), 2)
  21. * //=> Wed Apr 02 2014 00:00:00
  22. */
  23. export function setQuarter(date, quarter) {
  24. const _date = toDate(date);
  25. const oldQuarter = Math.trunc(_date.getMonth() / 3) + 1;
  26. const diff = quarter - oldQuarter;
  27. return setMonth(_date, _date.getMonth() + diff * 3);
  28. }
  29. // Fallback for modularized imports:
  30. export default setQuarter;