Skip to content

Instantly share code, notes, and snippets.

@catamphetamine
Created December 30, 2019 15:08
Show Gist options
  • Save catamphetamine/c0e2f21f1063b11a90f5790eadfcefa4 to your computer and use it in GitHub Desktop.
Save catamphetamine/c0e2f21f1063b11a90f5790eadfcefa4 to your computer and use it in GitHub Desktop.
/**
* Returns the week number for this date.
* https://stackoverflow.com/questions/9045868/javascript-date-getweek
* @param {Date} date
* @param {number} [dowOffset] — The day of week the week "starts" on for your locale - it can be from `0` to `6`. By default `dowOffset` is `0` (USA, Sunday). If `dowOffset` is 1 (Monday), the week returned is the ISO 8601 week number.
* @return {number}
*/
export default function getWeek(date, dowOffset = 0) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */
const newYear = new Date(date.getFullYear(), 0, 1);
let day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = (day >= 0 ? day : day + 7);
const daynum = Math.floor((date.getTime() - newYear.getTime() -
(date.getTimezoneOffset() - newYear.getTimezoneOffset()) * 60000) / 86400000) + 1;
//if the year starts before the middle of a week
if (day < 4) {
const weeknum = Math.floor((daynum + day - 1) / 7) + 1;
if (weeknum > 52) {
const nYear = new Date(date.getFullYear() + 1, 0, 1);
let nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
/*if the next year starts before the middle of
the week, it is week #1 of that year*/
return nday < 4 ? 1 : 53;
}
return weeknum;
}
else {
return Math.floor((daynum + day - 1) / 7);
}
}
@reregaga
Copy link

omg

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment