Календарь

by Artem

HTML

<div id="calendar"></div>

CSS

table {
  border-collapse: collapse;
}

td,
th {
  border: 1px solid black;
  padding: 3px;
  text-align: center;
}

th {
  font-weight: bold;
  background-color: #E6E6E6;
}

JavaScript

'use strict';

function createCalendar(id, year, month) {
  const DAYS = ['пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс'];

  function getDay(num) {
    return num === 0 ? 6 : num - 1;
  }

  var elem = document.getElementById(id);

  const calendar = document.createElement('table');
  const thead = calendar.createTHead();
  const row = thead.insertRow(0);
  for (let i = 0; i < 7; i++) {
    const cell = document.createElement('th');
    cell.appendChild(document.createTextNode(DAYS[i]));
    row.appendChild(cell);
  }

  const tbody = calendar.createTBody();
  const firstDay = new Date(year, month - 1);
  const lastDay = new Date(year, month, 0);
  const weeks = Math.ceil(lastDay.getDate() / 7);

  let currentDate = firstDay.getDate();
  let currentDay = getDay(firstDay.getDay());

  console.log(lastDay.getDate());
  outer: for (let i = 0; i <= weeks; i++) {
    const row = tbody.insertRow(-1);
    for (let j = 0; j < 7; j++) {
      const cell = row.insertCell(j);
      if (currentDay === j) {
  			//if (currentDate > lastDay.getDate()) continue;
        cell.textContent = currentDate;
        currentDate++;
        currentDay++;
        if (currentDay === 7) currentDay = 0;
        if (currentDate > lastDay.getDate()) break outer;
      }
    }
  }

  elem.appendChild(calendar);
}

createCalendar('calendar', 1996, 11);