2011-08-18 17 views
7

En este momento, tengo esto en mi página:Dada una fecha de inicio y fin, crear una matriz de las fechas entre los dos

<script type="text/javascript"> 
    $(document).ready(function() { 
     var days = [ 
      { Date: new Date($('#hfEventStartDate').val()) }, 
      { Date: new Date($('#hfEventEndDate').val()) } 
     ]; 
    }); 
</script> 

<asp:HiddenField ID="hfEventStartDate" runat="server" /> 
<asp:HiddenField ID="hfEventEndDate" runat="server" /> 

Soy la creación hfEventStartDate y hfEventEndDate cuando se carga la página. Con mi código en este momento, crea una matriz con dos valores: la fecha de inicio y la fecha de finalización. Pero me gustaría que la matriz contenga todas las fechas intermedias. ¿Cómo puedo hacer eso?

+0

Inténtelo algo por sí mismo antes de publicar una pregunta; la mayoría de la gente aquí fruncir el ceño ante las solicitudes de código como este. –

Respuesta

16

Se podría hacer uso de setDate(getDate() + 1) a 'iterate' sobre todos los días: http://jsfiddle.net/pimvdb/4GeFD/1/.

$("#hfEventStartDate").val(new Date - 24 * 3600 * 1000 * 7 - 1); 
$("#hfEventEndDate").val(new Date - 0); 

function getAllDays() { 
    var s = new Date($('#hfEventStartDate').val() - 0); 
    var e = new Date($('#hfEventEndDate').val() - 0); 
    var a = []; 

    while(s < e) { 
     a.push(s); 
     s = new Date(s.setDate(
      s.getDate() + 1 
     )) 
    } 

    return a; 
}; 

alert(getAllDays().join("\n")); 
7

Aquí hay una oportunidad: jsFiddle

var date1 = new Date(); 
var date2 = new Date(2010, 0, 1); 
var day; 
var between = [date1]; 

while(date2 <= date1) { 
    day = date1.getDate() 
    date1 = new Date(date1.setDate(--day)); 
    between.push(date1); 
} 

console.log(between); 
3
 start = new Date("August 13,2011"); 
     future = new Date("October 13, 2011"); 
     range = [] 
     mil = 86400000 //24h 
     for (var i=start.getTime(); i<future.getTime();i=i+mil) { 

      range.push(new Date(i)) 

     //or for timestamp 
     //range.push(i) 
     } 
3

tratar momment.js y twix

var itr = moment.twix(new Date('2012-01-15'),new Date('2012-01-20')).iterate("days"); 
var range=[]; 
while(itr.hasNext()){ 
    range.push(itr.next().toDate()) 
} 
console.log(range); 

vivo: http://jsfiddle.net/aswani/GNPQc/

0

Esto funcionó para mí también:

$("#hfEventStartDate").val(new Date - 24 * 3600 * 1000 * 7 - 1); 
$("#hfEventEndDate").val(new Date - 0); 

function getAllDays() { 
    var s = new Date($('#hfEventStartDate').val() - 0); 
    var e = new Date($('#hfEventEndDate').val() - 0); 
    var a = []; 
    while(s <= e) { 
     a.push(new Date(s)); 
     s.setDate(s.getDate() + 1); 
    } 

    return a; 
}; 

alert(getAllDays().join("\n")); 

es el mismo código ese pimvdb publicado con algunos cambios menores, pero da un resultado diferente. Me tomó 4 horas tratando de entender por qué, y esto es lo que creo que sucede con el código de pimvdb:

1 loop 
a[0] = S1 = $("#hfEventStartDate").val(new Date - 24 * 3600 * 1000 * 7 - 1); 
//2013-09-01 

2 loop 
a[0] = s1.setDate(s1.getDate() + 1); // 2013-09-02 
a[1] = s2 = new Date(s1.setDate(s1.getDate() + 1)) // 2013-09-02 

3 loop 
a[0] = s1; // 2013-09-02 
a[1] = s2.setDate(s2.getDate() + 1); // 2013-09-03 
a[2] = s3 = new Date(s2.setDate(s2.getDate() + 1)) // 2013-09-03 

and so on... 

No estoy seguro si esto estaba destinado deliberadamente por pimvdb pero su código de izquierdas a cabo el día de inicio, la cual en mi ejemplo sería 2013-09-01. Pero incluso si fue intencionado, ¿por qué no dejar el último día también? al menos eso es lo que (< e) parecía ser la intención, pero el último día está incluido en la matriz final.

Lo siento, puedo estar equivocado, nunca he trabajado con programación orientada a objetos, pero tratar de entender por qué un [0] estaba cambiando en el segundo ciclo después de haber sido asignado en el primer puño me volvió absolutamente loco . Espero no estar tan equivocado. Gracias.

2

He leído la respuesta dada y esto es con lo que salí. Tenga en cuenta que empecé a partir de la respuesta @pimvdb

// return an array composed of a list of the days' number 
// from 1 month ago until today, not included 
function getAllDays() { 
var e = moment(); 
var s = moment().subtract('months', 1); 
var a = [] 
    // While the updated start date is older, perform the loop. 
    while(s.isBefore(e)) { 
    // Update the format according to moment js documentations format(). 
    a.push(s.format("MMM - DD")); 
    s = s.add('days', 1); 
    } 
return a; 
} 

Simplemente llame a la función de cualquier parte del código:

getAllDays(); 

ver también: MomentJs library

Cuestiones relacionadas