views:

44

answers:

2

Hello. I need no generate a full daterange in JScript from a given Startdate to now.

Startdate: 2010-03-25
2010-03-26
2010-03-27
...
2010-05-30

I am very confused with Javascript Date.

best would be a function to give a daterange as params and getting an Array of the formatted date back, something like that:

range[0] = 2010-03-25
range[1] = 2010-03-26
range[2] = 2010-03-27
    ...
range[x] = 2010-05-30

I am so confused thanks for any hint marcus

+1  A: 

The following snippet will store the dates as strings in the format you want in the dateStrings array:

var startDate = new Date(2010, 03, 25);
var endDate = new Date(2010, 04, 02);

var newDate = startDate;
var dateStrings = new Array()

while (newDate <= endDate){
  str = newDate.getFullYear() + "-" +
        (newDate.getMonth() + 1) + "-" +
      newDate.getDate();         
  dateStrings.push(str);
  newDate.setDate(newDate.getDate()+1);
}

If you want to keep the date objects in an array, and format the strings yourself at a later date (pun intended), do something like the following:

var startDate = new Date(2010, 03, 25);
var endDate = new Date(2010, 04, 02);

var newDate = startDate;
var range = new Array()

while (newDate <= endDate){
  range.push(new Date(newDate));
  newDate.setDate(newDate.getDate()+1);
}
fmark
I like the second solution because you can use a map from Date to String to get the final result (https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Map). And I'll take any excuse I can get to use map or filter or zip or foldl :-D.
jasonmp85
awesome! thank you so much. I first thought I need to calculate with milliseconds and stuff.many many thanks!
Marcus
A: 

Let's try this. This function should return a string array of the type you requested. I copy the date to keep my function from having any side effect.

function getDateRange(startDate) {
    var theDate = new Date(startDate.getTime());
    var range = [];
    var now = new Date();

    while(theDate.getTime() < now.getTime()) {
        var string = theDate.getFullYear() + "-" +
                     (theDate.getMonth() + 1) + "-" +
                     theDate.getDate();
        range.push(string);
        theDate.setTime(theDate.getTime() + 86400000);
    }

    return range;
}

References

Date - MDC

jasonmp85