Algorithm - How to get the days in a week JS

5

I have the following situation: I need to set the days of each week within a month, creating an array of JSON objects.

Each position would correspond to a week, for example if there were 5 weeks I would have an array of 5 positions, where each position would be an object where the day of the week would be the key, and the day of the month the value of this key. / p>

example:

0: {segunda:02/05, terça: 03/05 ...}
1: {...quinta:n/n, sexta:n/n}

I tried to do this using the Date date object but I could not, how could I create this algorithm?

    
asked by anonymous 12.05.2016 / 16:16

1 answer

2

As I suggested in the comments take a look at this project js-Calendar ( demo ), because I think it does a lot of what you need. It is a date generator with weekdays, etc.

But answering the specific question you can do this:

var diasSemana = ['Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sabado', 'Domingo'];

function diaSemana(nr) {
    return diasSemana[nr % 7]; // dar nomes ao numero do dia de semana
}

function diasMes(ano, mes) {
    var semanas = []; // array a preencher
    var semana = {};
    var diaUm = new Date(ano, mes - 1); // dia um do mês
    var inicioSemana = diaUm.getDay() - 1; // numero do dia da semana (começando na segunda)
    var ultimoDia = new Date(ano, mes, -1).getDate(); // quantidade de dias no mês
    for (var i = 1; i <= ultimoDia; i++) {
        var dia = diaSemana(inicioSemana++); // dar nome ao dia da semana
        semana[dia] = [i, mes].join('/'); // dia do mês / mês
        if (i % 7 == 0) { // caso mude a semana
            semanas.push(semana);
            semana = {}
        } else {
            if (i == ultimoDia) semanas.push(semana); // juntar os ultimos dias
        }
    }
    return semanas;
}

var janeiro = diasMes(2016, 1);
alert(JSON.stringify(janeiro, null, 4));

jsFiddle: link

I made this code now, test it to see if it does not have a hidden bug.

    
12.05.2016 / 17:32