setYear.cjs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. "use strict";
  2. exports.setYear = setYear;
  3. var _index = require("./constructFrom.cjs");
  4. var _index2 = require("./toDate.cjs");
  5. /**
  6. * The {@link setYear} function options.
  7. */
  8. /**
  9. * @name setYear
  10. * @category Year Helpers
  11. * @summary Set the year to the given date.
  12. *
  13. * @description
  14. * Set the year to the given date.
  15. *
  16. * @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).
  17. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  18. *
  19. * @param date - The date to be changed
  20. * @param year - The year of the new date
  21. * @param options - An object with options.
  22. *
  23. * @returns The new date with the year set
  24. *
  25. * @example
  26. * // Set year 2013 to 1 September 2014:
  27. * const result = setYear(new Date(2014, 8, 1), 2013)
  28. * //=> Sun Sep 01 2013 00:00:00
  29. */
  30. function setYear(date, year, options) {
  31. const date_ = (0, _index2.toDate)(date, options?.in);
  32. // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
  33. if (isNaN(+date_)) return (0, _index.constructFrom)(options?.in || date, NaN);
  34. date_.setFullYear(year);
  35. return date_;
  36. }