index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import toInteger from "../_lib/toInteger/index.js";
  2. import toDate from "../toDate/index.js";
  3. import requiredArgs from "../_lib/requiredArgs/index.js";
  4. /**
  5. * @name setYear
  6. * @category Year Helpers
  7. * @summary Set the year to the given date.
  8. *
  9. * @description
  10. * Set the year to the given date.
  11. *
  12. * ### v2.0.0 breaking changes:
  13. *
  14. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  15. *
  16. * @param {Date|Number} date - the date to be changed
  17. * @param {Number} year - the year of the new date
  18. * @returns {Date} the new date with the year set
  19. * @throws {TypeError} 2 arguments required
  20. *
  21. * @example
  22. * // Set year 2013 to 1 September 2014:
  23. * const result = setYear(new Date(2014, 8, 1), 2013)
  24. * //=> Sun Sep 01 2013 00:00:00
  25. */
  26. export default function setYear(dirtyDate, dirtyYear) {
  27. requiredArgs(2, arguments);
  28. var date = toDate(dirtyDate);
  29. var year = toInteger(dirtyYear); // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
  30. if (isNaN(date.getTime())) {
  31. return new Date(NaN);
  32. }
  33. date.setFullYear(year);
  34. return date;
  35. }