Calculate on which days of the week the days of the month fall

Asked

Viewed 2,089 times

4

I created a javascript function that assembles a calendar. I need this calendar to assemble according to the number and days of the week of the given month. Ex(August 1 fell on a Tuesday). I also need that when I change the month my schedule will mount according to the selected month. Follows the code.

Function that mounts my agenda

$(document).ready(function () {
    var str = '';
    var aux = 1;
    var tr = '';
    var tbl = $('#calendar');

    for (var i = 1; i < 32; i++) {

        if (aux == 1) {
            tr = '<tr>';
        }
        str += tr + '<td class="calendario btnExibirDetalhes" data-toggle="modal" data-target="#Modal" position="static">' + i + '</td>';
        if (aux == 7) {

            str = str + tr;
            aux = 0;
        }
        aux++;
        tr = '';
    }
    if (tr == '') {
        tr = '</tr>';
        str = str + tr
    }
    tbl.append(str);
});

Function that arrow the current month

 $(document).ready(function () {
    monName = new Array("Janeiro",
                        "Fevereiro",
                        "Março",
                        "Abril",
                        "Maio",
                        "Junho",
                        "Julho",
                        "Agosto",
                        "Setembro",
                        "Outubro",
                        "Novembro",
                        "Dezembro")
    hoje = new Date();
    var preenchemes = $('#mes');
    preenchemes.append(monName[hoje.getMonth()]);

});
  • Take a look here: https://jqueryui.com/datepicker/

3 answers

6


I don’t know if I understand, but if you’re having trouble getting the day of the week that your Dates, you can use the method Date.prototype.getDay() which returns the value of the day of the week to the date, being:

Valor | Dia da semana
------|---------------
  0   |    Domingo
  1   |    Segunda
  2   |    Terça
  3   |    Quarta
  4   |    Quinta
  5   |    Sexta
  6   |    Sábado

For example:

var d = new Date();
var n = d.getDay();
document.getElementById("result").innerHTML = n;
<p id="result"></p>

Edit

As per comment you need to:

function daysInMonth(month, year) {
  return new Date(year, month + 1 /* para ir a proximo */ , 0 /* para voltar ao ultimo dia do mês anterior*/ ).getDate();
}

var d = new Date();
var result = daysInMonth(d.getMonth(), d.getFullYear());
document.getElementById("result").innerHTML = result;
<p id="result"></p>

  • And what day falls 1°a certain month’s day, almost in the same idea, something like that:

function firstDayWeekInMonth(month,year) {
   return new Date(year, month, 1).getDay();
}

var d = new Date();
var result = firstDayWeekInMonth(d.getMonth(), d.getFullYear());
document.getElementById("result").innerHTML = result;
<p id="result"></p>

Note: Whenever you are manipulating Dates, remember that the months do not base 0 (0-based).

  • 2

    0 = Sunday, 1 = Monday, and so on.

  • So that’s still not it. I have in my html the static days of the week. What I need to do is check how many days for example has the month of August and what day of the week fell day 1, for my schedule to be set from this.

  • @Raphaelgumm, I added information to my original reply as your clarification in the reply comments. Check if it helps you!

  • Perfect @Fernando, that’s exactly what I needed. Thank you very much.

4

to take the total of days of the month, we can use a small Trick, which is to take the day 0 of next month.

var month = document.getElementById("month");
var agenda = document.querySelector("#agenda tbody");
var lblDiaSemana = document.getElementById("lblDiaSemana");
var lblTotalDias = document.getElementById("lblTotalDias");
var tmplAgenda = Handlebars.compile(document.getElementById("tmplAgenda").innerHTML);
var diasSemana = [
  "Domingo",
  "Segunda",
  "Terça",
  "Quarta",
  "Quinta",
  "Sexta",
  "Sábado"
];

month.addEventListener("change", function (event) {
  var ano = parseInt(event.target.value.split("-")[0]);
  var mes = parseInt(event.target.value.split("-")[1]);

  var diaPrimeiro = new Date(ano, mes - 1, 1).getDay();
  var totalDias = new Date(ano, mes, 0).getDate();
  var mes = [];
  var inicio = diaPrimeiro;

  for (var diaMes = 0; diaMes < totalDias;) {
    var semana = [];
    for (var diaSemana = inicio; diaSemana < 7 && diaMes < totalDias; diaSemana++) {
      semana[diaSemana] = diaMes + 1;
      diaMes++;
    }
    mes.push(semana);
    inicio = 0;
  }
  

  // 00/09/2015 = 31/08/2015 ;D
  lblTotalDias.innerHTML = totalDias;
  lblDiaSemana.innerHTML = diasSemana[diaPrimeiro];
  agenda.innerHTML = tmplAgenda(mes);  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.js"></script>
<div>
  <input id="month" type="month" />
</div>
<div>
  Dia da Semana: <span id="lblDiaSemana"></span>
</div>
<div>
  Total de Dias: <span id="lblTotalDias"></span>
</div>
<div>
  <table id="agenda">
    <thead>
      <tr>
        <td>Domingo</td>
        <td>Segunda</td>
        <td>Terça</td>
        <td>Quarta</td>
        <td>Quinta</td>
        <td>Sexta</td>
        <td>Sábado</td>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
</div>

<script id="tmplAgenda" type="text/x-handlebars-template">
  {{#each this}}
  <tr>
    {{#each this}}
    <td class="calendario btnExibirDetalhes" data-toggle="modal" data-target="#Modal" position="static">
      {{this}}
    </td>
    {{/each}}
  </tr>
  {{/each}}
</script>

3

How to get the amount of days of the month:

function daysInMonth(month,year) {
    return new Date(year, month, 0).getDate();
}

//Pegando a quantidade de dias do mês de fevereiro de 2015
alert(daysInMonth(2,2015)); // 28 

How to take the day of the week:

function getDayOfWeek(month, year){
    return new Date(year, (month-1), 1).getDay();
}

alert(getDayOfWeek(2,2015)); // 5 que é Sexta-Feira

Setting values in the same function:

function getMonthInfos(month, year){
    var monthDays = daysInMonth(month,year);
    var weekDay = getDayOfWeek(month, year);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.