1

How to Find out week number of the month from Date...

(Date/7) and ceil/floor(Date/7) is not working for month Dec-2019 ( or any month which have 1 day is Sunday )...

My code:

var day = new Date($("#convDate").val()).getDay();
var week = 0 | new Date($("#convDate").val()).getDate() / 7;

week = Math.ceil(week);

if (week == 1 || week == 3) {
  if (day == 6) {
    alert("Half Day");
  }
}

alert("Submit");
return false;
Tiffany
  • 680
  • 1
  • 15
  • 31
qɐʇǝɥɐW
  • 347
  • 3
  • 17
  • Have you checked [this](https://stackoverflow.com/questions/3280323/get-week-of-the-month)? – tomerpacific Dec 17 '19 at 13:56
  • https://stackoverflow.com/questions/5853380/php-get-number-of-week-for-month – BCM Dec 17 '19 at 13:59
  • So you want to know which week of the month "today" is? For example, December 1, 2019 would be in week 1 of December.. and December 17, 2019 would be in week 3 of the month? – Matt Oestreich Dec 17 '19 at 14:04
  • Does your week start with Sunday or Monday? Are you using weeks defined in ISO 8601? – some Dec 17 '19 at 14:05
  • Are you not just trying to get ['W' (the ISO-8601 week number of year)](https://www.php.net/manual/en/function.date.php) ? e.g. `Datetime::format('W')` – CD001 Dec 17 '19 at 14:11

2 Answers2

1
Date.prototype.getMDay = function() {
  return (this.getDay() + 6) %7;
}

Date.prototype.getISOYear = function() {
  var thu = new Date(this.getFullYear(), this.getMonth(), this.getDate()+3-this.getMDay());
  return thu.getFullYear();
}

Date.prototype.getISOWeek = function() {
  var onejan = new Date(this.getISOYear(),0,1);
  var wk = Math.ceil((((this - onejan) / 86400000) + onejan.getMDay()+1)/7);
  if (onejan.getMDay() > 3) wk--;return wk;
}

week = (new Date('Dec 2019')).getISOWeek();  //48
jspit
  • 7,276
  • 1
  • 9
  • 17
1

I Found Solution Just Right Now, From Get week number of the month from date (weeks starting on Mondays)

Answered By Avraham [ Thanks a lot.. ]

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);
}
qɐʇǝɥɐW
  • 347
  • 3
  • 17