setYear.js 1.0 KB

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