index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. var parse = require('../parse/index.js')
  2. var startOfISOYear = require('../start_of_iso_year/index.js')
  3. var differenceInCalendarDays = require('../difference_in_calendar_days/index.js')
  4. /**
  5. * @category ISO Week-Numbering Year Helpers
  6. * @summary Set the ISO week-numbering year to the given date.
  7. *
  8. * @description
  9. * Set the ISO week-numbering year to the given date,
  10. * saving the week number and the weekday number.
  11. *
  12. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  13. *
  14. * @param {Date|String|Number} date - the date to be changed
  15. * @param {Number} isoYear - the ISO week-numbering year of the new date
  16. * @returns {Date} the new date with the ISO week-numbering year setted
  17. *
  18. * @example
  19. * // Set ISO week-numbering year 2007 to 29 December 2008:
  20. * var result = setISOYear(new Date(2008, 11, 29), 2007)
  21. * //=> Mon Jan 01 2007 00:00:00
  22. */
  23. function setISOYear (dirtyDate, dirtyISOYear) {
  24. var date = parse(dirtyDate)
  25. var isoYear = Number(dirtyISOYear)
  26. var diff = differenceInCalendarDays(date, startOfISOYear(date))
  27. var fourthOfJanuary = new Date(0)
  28. fourthOfJanuary.setFullYear(isoYear, 0, 4)
  29. fourthOfJanuary.setHours(0, 0, 0, 0)
  30. date = startOfISOYear(fourthOfJanuary)
  31. date.setDate(date.getDate() + diff)
  32. return date
  33. }
  34. module.exports = setISOYear