setYear.mjs 1.0 KB

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