javascriptlogicbootstrap-daterangepicker

How to get how many weeks and days in a month in Javascript and logic formulation


So I have this daterangepicker In which by default the date is 2020/04/15 and besides it is the <select> element that has choices of "Daily", "Weekly", "Monthly" (Please see picture below).

enter image description here

Is there any way to compute for which day a week starts in april and how many days april have whenever I clicked the weekly or the monthly in the dropdown besides the daterangepicker.

For example:

April has 30 days and week 1 starts at April 6 while in March it has 31 days and week 1 starts at March 2

I know that every month has 4 weeks in it but the question is how can i get the day that starts the week in every month. Is there any way to calculate it in javascript? Or should i just start with day 1 then just count 7 days?


Solution

  • a basic one...

    // prepare select for demo
    for(let i=2015; i<2026;i++) eYear.add( new Option(i, i) )
    eYear.value = 2020
    
    function calcMonthInfos( month=0, year=2020 ) // default on January 2020
      {
      let nDay = 0, lastDay = 28, wDay, wMonth
        ; 
      do { wDay = new Date(year,month,++nDay).getDay() }
      while (wDay != 1)  // sunday is day 0 , monday day 1
        ;
      do { wMonth = new Date(year,month,++lastDay).getMonth() }
      while (wMonth == month)  //  check month changing
        ;
      return ({ monday1fst: nDay, monthDays:--lastDay })
      }  
    
    
    // démo code :
    btGetInfo.onclick=_=>
      {
      let monthInfo = calcMonthInfos(parseInt(eMonth.value), parseInt(eYear.value) )
        , MonthName = eMonth.options[eMonth.selectedIndex].text
        ;
      info.textContent = `First monday of ${MonthName} ${eYear.value} ` 
                       + `is the ${monthInfo.monday1fst}, ` 
                       + `this month has ${monthInfo.monthDays} days`
      }
    <select id="eMonth">
      <option value="0"> January </option>
      <option value="1"> February</option>
      <option value="2"> March</option>
      <option value="3"> April</option>
      <option value="4"> May</option>
      <option value="5"> June</option>
      <option value="6"> July</option>
      <option value="7"> August</option>
      <option value="8"> September</option>
      <option value="9"> October</option>
      <option value="10"> November</option>
      <option value="11"> December</option>
      </select>
    
    <select id="eYear"></select>
    
    <br><br>
     
    <button id="btGetInfo">get info</button>
    
    <p id="info">...</p>