JavaScript Program to Display Current Month Calendar

JavaScript Program to Display Current Month Calendar

Here is an example of a JavaScript program that displays a calendar for the current month:

Display Current Month Calendar using JavaScript Example

<!DOCTYPE html>
<html>
  <head>
    <title>Month Calendar</title>
  </head>
  <body>
    <table>
      <thead>
        <tr>
          <th>Sun</th>
          <th>Mon</th>
          <th>Tue</th>
          <th>Wed</th>
          <th>Thu</th>
          <th>Fri</th>
          <th>Sat</th>
        </tr>
      </thead>
      <tbody id="calendar-body"></tbody>
    </table>

    <script>
      // Get the current date
      const date = new Date();

      // Get the current month and year
      const month = date.getMonth();
      const year = date.getFullYear();

      // Get the first day of the month
      const firstDay = new Date(year, month, 1);

      // Get the day of the week of the first day (0 = Sunday, 1 = Monday, etc.)
      const startDay = firstDay.getDay();

      // Get the number of days in the month
      const numDays = new Date(year, month + 1, 0).getDate();

      // Get a reference to the calendar body element
      const calendarBody = document.querySelector('#calendar-body');

      // Create a table row for each week
      for (let i = 0; i < 6; i++) {
        // Create a table cell for each day
        const row = document.createElement('tr');
        for (let j = 0; j < 7; j++) {
          const cell = document.createElement('td');
          const day = i * 7 + j - startDay + 1;
          if (day > 0 && day <= numDays) {
            cell.textContent = day;
          }
          row.appendChild(cell);
        }
        calendarBody.appendChild(row);
      }
    </script>
  </body>
</html>

When this program is run, it will display a calendar for the current month in a table in the browser window. Each cell in the table represents a day of the month, with Sunday as the first column and Saturday as the last column. For example, if the current month is December 2022, the program will output a calendar similar to the following:

Sun	Mon	Tue	Wed	Thu	Fri	Sat
                                1	2	3
4	5	6	7	8	9	10
11	12	13	14	15	16	17
18	19	20	21	22	23	24
25	26	27	28	29	30	31

Related:

  1. What are Array Methods in JavaScript?
  2. Check if Object is Not Empty in JavaScript