Question:
I created a javascript function that assembles a schedule. I need this schedule to assemble according to the amount and days of the week in a given month. Ex ( August 1st fell on a Tuesday ). I also need that when I change the month my schedule assembles according to the selected month. Follow the code.
Function that assembles my schedule
$(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 sets 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()]);
});
Answer:
I'm not sure I understand, but if you're having trouble getting the day of the week your Dates are, you can use the Date.prototype.getDay()
method which returns the day of the week value for the date, such as:
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 the comment you need:
- Know how many days there is in a given month – which you can do according to this post on SOen , like this:
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 which day falls on the 1st of a given month, almost in the same idea, something like this:
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 manipulating Dates, remember that months are not base 0 (
0-based
) .