Javascript loop between date ranges

Javascript loop between date ranges

Asked on December 19, 2018 in Javascript.
Add Comment


  • 3 Answer(s)

    Try this solution,

    Actually, There is a way to do it by creating use of the way adding one day,  if it is necessary it causes the date to roll over to the next month, and without messing around with milliseconds.

    var now = new Date();
    var daysOfYear = [];
    for (var d = new Date(2012, 0, 1); d <= now; d.setDate(d.getDate() + 1)) {
        daysOfYear.push(new Date(d));
    }
    

    Remember one thing, if we want to store the date, it is need to make a new one , otherwise in the loop we will end up with each stored date being the final value.

    Answered on December 19, 2018.
    Add Comment

    This is the simplest solution ever,

    var start = new Date("02/05/2013");
    var end = new Date("02/10/2013");
     
    var loop = new Date(start);
    while(loop <= end){
        alert(loop);
     
        var newDate = loop.setDate(loop.getDate() + 1);
        loop = new Date(newDate);
    }
    
    Answered on December 19, 2018.
    Add Comment

    Using this code we will get the answer,

    In the case of startDate and endDate are positive date objects we have to convert them as milliseconds since Jan 1, 1970, which means the accurate date of jan1 , 1970.

    var startTime = startDate.getTime(), endTime = endDate.getTime();
    

    After that we could incrementing loopTime by 86400000 (1000*60*60*24) which means one day have 86400000 milliseconds:

    for(loopTime = startTime; loopTime < endTime; loopTime += 86400000)
    {
        var loopDay=new Date(loopTime)
        //use loopDay as you wish
    }
    
    Answered on December 19, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.