setQuarter.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { setMonth } from "./setMonth.js";
  2. import { toDate } from "./toDate.js";
  3. /**
  4. * The {@link setQuarter} function options.
  5. */
  6. /**
  7. * @name setQuarter
  8. * @category Quarter Helpers
  9. * @summary Set the year quarter to the given date.
  10. *
  11. * @description
  12. * Set the year quarter to the given date.
  13. *
  14. * @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).
  15. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  16. *
  17. * @param date - The date to be changed
  18. * @param quarter - The quarter of the new date
  19. * @param options - The options
  20. *
  21. * @returns The new date with the quarter set
  22. *
  23. * @example
  24. * // Set the 2nd quarter to 2 July 2014:
  25. * const result = setQuarter(new Date(2014, 6, 2), 2)
  26. * //=> Wed Apr 02 2014 00:00:00
  27. */
  28. export function setQuarter(date, quarter, options) {
  29. const date_ = toDate(date, options?.in);
  30. const oldQuarter = Math.trunc(date_.getMonth() / 3) + 1;
  31. const diff = quarter - oldQuarter;
  32. return setMonth(date_, date_.getMonth() + diff * 3);
  33. }
  34. // Fallback for modularized imports:
  35. export default setQuarter;