How to generate a sequence of dates, starting dates and end dates?

3

Javascript and jQuery have been my tormentors. I have a hidden field that has start date and end date. How do I do this via javascript, a to fill a TD with the dates passed in that period, from the smallest (start_date) to the largest (date_final)?

    
asked by anonymous 04.04.2014 / 23:05

2 answers

2

You can do this:

var diaInicial = new Date($('#dataInicial').val()); // usar $('#ID').val() para ir buscar a data ao input
var diaFinal = new Date($('#dataFinal').val());
var novaData = diaInicial;
var tabela = $('#codexpl'); // o ID da sua tabela

if (novaData > diaFinal) { // no caso de as datas estarem trocadas e para evitar um loop infinito
    novaData = diaFinal;
    diaFinal = diaInicial;
}

while (novaData < diaFinal) { // enquanto a data inicial for inferior à final
    novaData = new Date(novaData.getTime() + (24 * 60 * 60 * 1000)); // adicionar 24horas x 60 min x 60seg x 1000 milisegundos por dia

    // formatar a data para o formato aaaa-mm-dd
    dataFormatada = novaData.getFullYear() + '-' + (novaData.getMonth() + 1) + '-' + novaData.getDate(); 

    // adicionar novas linhas à tabela
    tabela.append('<tr><td>' + dataFormatada + '</td></tr>');
}

Live example

    
05.04.2014 / 08:45
1

You can do something like this:

data_inicio = new Date('2014, 03, 19');
data_fim = new Date('2014, 04, 13');
achou = false;
i = 0;

while (!achou)
{
    data_tmp = new Date();
    data_tmp.setDate(data_inicio.getDate()+i);
    document.getElementById('datas').innerHTML += data_tmp;
    i++;

    if (data_tmp > data_fim)
    {
        achou = true;
    }
}

Example: link

    
05.04.2014 / 03:22