index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import toInteger from "../toInteger/index.js";
  2. import toDate from "../../toDate/index.js";
  3. import startOfUTCWeek from "../startOfUTCWeek/index.js";
  4. import requiredArgs from "../requiredArgs/index.js"; // This function will be a part of public API when UTC function will be implemented.
  5. // See issue: https://github.com/date-fns/date-fns/issues/376
  6. export default function getUTCWeekYear(dirtyDate, dirtyOptions) {
  7. requiredArgs(1, arguments);
  8. var date = toDate(dirtyDate, dirtyOptions);
  9. var year = date.getUTCFullYear();
  10. var options = dirtyOptions || {};
  11. var locale = options.locale;
  12. var localeFirstWeekContainsDate = locale && locale.options && locale.options.firstWeekContainsDate;
  13. var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate);
  14. var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
  15. if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
  16. throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
  17. }
  18. var firstWeekOfNextYear = new Date(0);
  19. firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
  20. firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
  21. var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, dirtyOptions);
  22. var firstWeekOfThisYear = new Date(0);
  23. firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
  24. firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
  25. var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, dirtyOptions);
  26. if (date.getTime() >= startOfNextYear.getTime()) {
  27. return year + 1;
  28. } else if (date.getTime() >= startOfThisYear.getTime()) {
  29. return year;
  30. } else {
  31. return year - 1;
  32. }
  33. }