index.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var parse = require('../parse/index.js')
  2. var startOfISOWeek = require('../start_of_iso_week/index.js')
  3. /**
  4. * @category ISO Week-Numbering Year Helpers
  5. * @summary Get the ISO week-numbering year of the given date.
  6. *
  7. * @description
  8. * Get the ISO week-numbering year of the given date,
  9. * which always starts 3 days before the year's first Thursday.
  10. *
  11. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  12. *
  13. * @param {Date|String|Number} date - the given date
  14. * @returns {Number} the ISO week-numbering year
  15. *
  16. * @example
  17. * // Which ISO-week numbering year is 2 January 2005?
  18. * var result = getISOYear(new Date(2005, 0, 2))
  19. * //=> 2004
  20. */
  21. function getISOYear (dirtyDate) {
  22. var date = parse(dirtyDate)
  23. var year = date.getFullYear()
  24. var fourthOfJanuaryOfNextYear = new Date(0)
  25. fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4)
  26. fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0)
  27. var startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear)
  28. var fourthOfJanuaryOfThisYear = new Date(0)
  29. fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4)
  30. fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0)
  31. var startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear)
  32. if (date.getTime() >= startOfNextYear.getTime()) {
  33. return year + 1
  34. } else if (date.getTime() >= startOfThisYear.getTime()) {
  35. return year
  36. } else {
  37. return year - 1
  38. }
  39. }
  40. module.exports = getISOYear