Get week number of the month from date (weeks starting on Mondays)

丶灬走出姿态 提交于 2019-12-24 13:28:49

问题


I have to find week number of the month from given date using JavaScript. Week start is Monday.

I have tried the code below but not getting accurate result.

function getWeekNumber(date) {
  var monthStartDate = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
  monthStartDate = new Date(monthStartDate);
  var day = monthStartDate.getDay();
  date = new Date(date);
  var date = date.getDate();

  let weekNumber = Math.ceil((date + (day)) / 7);
  return (weekNumber == 0) ? 1 : weekNumber;
}

var week = getWeekNumber('2020-04-04');
console.log(week);

回答1:


Try this one

function getWeek(date) {
  let monthStart = new Date(date);
  monthStart.setDate(0);
  let offset = (monthStart.getDay() + 1) % 7 - 1; // -1 is for a week starting on Monday
  return Math.ceil((date.getDate() + offset) / 7);
}
getWeek(new Date(2019, 2, 14))



回答2:


You could find the week number of the month for weeks starting on Monday (in line with the ISO week date system) by rolling the input date back to the previous Monday and then dividing the Monday date by 7 and rounding up to determine which week of the month the date falls in.

This approach will properly handle dates at the beginning of a month which actually fall in the last week of the previous month. For instance, 2020-04-04 is a Saturday in the week starting on 2020-03-30 (Monday), so it should return week 5 since it is part of the 5th week of March (and not part of the 1st week of April which starts on 2020-04-06, the first Monday in April).

For example (the split bit at the beginning is just to parse the date string rather than relying on new Date() to parse the string since that is not recommended due to browser inconsistencies):

const monthWeek = (s) => {
  let [y, m, d] = s.split('-'); // parse date string
  let date = new Date(y, m - 1, d); // create date object
  date.setDate(d - ((date.getDay() + 6) % 7)); // adjust date to previous Monday
  return Math.ceil(date.getDate() / 7); // return week number of the month
}

console.log(monthWeek('2020-04-04'));
// 5
console.log(monthWeek('2020-04-07'));
// 1


来源:https://stackoverflow.com/questions/55163345/get-week-number-of-the-month-from-date-weeks-starting-on-mondays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!