2

I'm stacked with one problem.

I have an array of data ranges:

var range_date_off=['31/03/2013','03/04/2013'];

I need to convert this into this:

var dates_off=['31/03/2013','01/04/2013','02/04/2013','03/04/2013'];

I started doing it with a loop, but the problem becomes when the month jumps to the other, any idea?

Claire Nielsen
  • 1,881
  • 1
  • 14
  • 31
jsertx
  • 636
  • 7
  • 17

4 Answers4

4

I'm using date.js here:

range = ['31/03/2013','03/04/2013']

begin = Date.parseExact(range[0], 'dd/MM/yyyy')
end   = Date.parseExact(range[1], 'dd/MM/yyyy')

dates = []

while(begin <= end) {
    dates.push(begin.toString("dd/MM/yyyy"))
    begin.addDays(1)
}

Result:

["31/03/2013", "01/04/2013", "02/04/2013", "03/04/2013"]
georg
  • 211,518
  • 52
  • 313
  • 390
3

This is parsing the date using regx

var range_date_off=['31/03/2013','03/04/2013'];
var d1 = parseDate(range_date_off[0])
var d2= parseDate(range_date_off[1])

var days= [];
for (var dt = d1; dt <= d2; dt.setDate(dt.getDate() + 1)) {
    var fdt = new Date(dt)
    days.push ( fdt.getDate() + "/" + (fdt.getMonth() + 1) + "/" + fdt.getFullYear());
}

function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  return new Date(parts[2], parts[1]-1, parts[0]); 
}
Alidad
  • 5,463
  • 1
  • 24
  • 47
  • 2
    Worth mentioning (for people who might wonder how this works), that JS Date object handles exceeding boundaries itself – if `dt.setDate(dt.getDate() + 1)` is called on 31th of March, then adding a day this way automatically switches to the 1st of April. – CBroe Mar 27 '13 at 13:31
1

You can do it using UTC arithmetic:

var start = Date.UTC(2013, 2, 31);
var end = Date.UTC(2013, 3, 3);
var currDate = start;
var dates = [];
while (currDate <= end) {
    var d = new Date(currDate);
    dates.push((d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear()));
   currDate += (1000 * 60 * 60 * 24);
}

Note, javescript months start at 0 !

http://jsfiddle.net/hKxzw/

SteveP
  • 18,840
  • 9
  • 47
  • 60
-1

Month check .... if month = [1,3,5,6,7,8,10,12] must not be greater than 31 days and so on ....

Anthon
  • 69,918
  • 32
  • 186
  • 246
user1711797
  • 11
  • 1
  • 3