How to generate a sequence of dates from start and end dates?

Asked

Viewed 746 times

3

Javascript and jQuery have been my executioners. I have a field hidden that has initial date and final date. As I do via javascript, a for to go filling a TD with the dates passed in that period, from the smallest (initial date) to the largest (final date)?

  • How are the dates in your Hidden field? You probably need to convert string to Date pro to be able to increment the dates in the range.

  • @Gypsy I totally removed the reference to Asp.net mvc, since the question in the background is about js/jquery.

  • @bfavaretto Okay, quiet.

2 answers

2

You can do it like 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

1

You can do something like:

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: http://jsfiddle.net/BqM4L/1/

Browser other questions tagged

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