0

This is the function called on component loading. The functions return all months with having 31 days. February and months with 30 days are also returned with 31 days. How to limit the number of days 30 in months and February till 28 or 29 on leap year.

const getCalendarCells = (date, items) => {

  var cells = [];
  try {
    if (items === undefined || items === null) {
      items = {};
    }
    /*----- Finding start of the month -----*/
    var start = new Date();
    start.setMonth(date.getMonth());
    start.setFullYear(date.getFullYear());
    start.setDate(1);
    /*----- Finding start of the calendar date -----*/
    while (start.getDay() != 0) {
      start.setDate(start.getDate() - 1);
    }
    /*----- Finding all calendar day of weeks headers -----*/
    cells.push(['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']);
    /*----- Finding all calendar cells -----*/
    var weekCells = [];
    for (var i = 0; i <= 42; i++) {
      if (i > 0 && i % 7 === 0) {
        cells.push(weekCells);
        weekCells = [];
      }
      if (i === 42) {
        break;
      } else {
        var type = (start.getMonth() === date.getMonth() && start.getFullYear() === date.getFullYear()) ? 'THIS' : 'OTHER';
        weekCells.push({
          data: (type === 'THIS' ? items[start.getDate().toString()] : {}),
          value: new Date(start.toString()).getDate(),
          type: type
        });
        start.setDate(start.getDate() + 1);
      }
    }
    console.log(cells)
    setReport(cells);

  } catch (ex) {}

}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • I made you a snippet. Please add relevant HTML and CSS in a [mcve] – mplungjan Jan 31 '20 at 09:48
  • Does this answer your question? [What is the best way to determine the number of days in a month with JavaScript?](https://stackoverflow.com/questions/315760/what-is-the-best-way-to-determine-the-number-of-days-in-a-month-with-javascript) – AZ_ Jan 31 '20 at 09:49
  • Is using a external library like moment.js, Luxon or DayJS an option? – ClydeFrog Jan 31 '20 at 09:50
  • @ClydeFrog Huge waste. Just do `var end = new Date(start.getFullYear(),start.getMonth()+1,0)` – mplungjan Jan 31 '20 at 10:02
  • where should i add this line. this only returns me end date of one month. what if i need all moths date together? – dominic kizhakkarakat Jan 31 '20 at 11:17
  • Hi. I looked over your code, and while there is a lot of noise here, I don't see anything at all where you would get the behavior you described. It would help if you modified the function to be a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). As it currently is, we don't know what `items` or `setReport` are. Could it simply be that `items` is only indexed by day of month and you're confusing one month with another? I see you call `items[start.getDate().toString()]` so that would be like `items["31"]` (for example) – Matt Johnson-Pint Feb 04 '20 at 19:41

0 Answers0