setYear.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { constructFrom } from "./constructFrom.js";
  2. import { toDate } from "./toDate.js";
  3. /**
  4. * The {@link setYear} function options.
  5. */
  6. /**
  7. * @name setYear
  8. * @category Year Helpers
  9. * @summary Set the year to the given date.
  10. *
  11. * @description
  12. * Set the year 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 year - The year of the new date
  19. * @param options - An object with options.
  20. *
  21. * @returns The new date with the year set
  22. *
  23. * @example
  24. * // Set year 2013 to 1 September 2014:
  25. * const result = setYear(new Date(2014, 8, 1), 2013)
  26. * //=> Sun Sep 01 2013 00:00:00
  27. */
  28. export function setYear(date, year, options) {
  29. const date_ = toDate(date, options?.in);
  30. // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
  31. if (isNaN(+date_)) return constructFrom(options?.in || date, NaN);
  32. date_.setFullYear(year);
  33. return date_;
  34. }
  35. // Fallback for modularized imports:
  36. export default setYear;