-1

Consider I have an array of dates eg:

abc = [new Date("2015-03-01"),new Date("2015-03-02"),new Date("2015-03-03"),new Date("2015-03-04")]

output:

[Sun Mar 01 2015 05:30:00 GMT+0530 (India Standard Time), Mon Mar 02 2015 05:30:00 GMT+0530 (India Standard Time), Tue Mar 03 2015 05:30:00 GMT+0530 (India Standard Time), Wed Mar 04 2015 05:30:00 GMT+0530 (India Standard Time)]

I'm trying to push the difference between two dates and trying to store the data in a new array. Here is what I have tried,

var arr = [];
abc = [new Date("2015-03-01"),new Date("2015-03-01"),new Date("2015-03-02"),new Date("2015-03-03"),new Date("2015-03-04")];

for (let i = 0; i < abc.length-1; i++){
    arr.push((abc[i+1].getDate() - abc[i].getDate())+1)
}

And the output I'm getting is:

[1,2, 2, 2]

But I needed the output something like

[1,2,3,4] 

I need to append plus one to each date difference. How can I achieve that?

Musthafa
  • 542
  • 1
  • 9
  • 25
  • 3
    do you want to get the difference between the first date and every other date in the array? Because currently, you're getting the difference between two neighbouring dates – Nick Parsons Jan 21 '20 at 08:38

2 Answers2

4

Dates in the format YYYY-MM-DD are parsed as UTC, where every day (in ECMAScript) is exactly 8.64e7 ms long making simple arithmetic, well, simple. :-)

Since the dates are whole days and treated as UTC, you can just subtract the dates from each other and divide by 8.64e7 to get whole days difference.

Also, you seem to want the difference from the first date, so hold that constant, e.g.

let arr = [];
let abc = [new Date("2015-03-01"),new Date("2015-03-01"),new Date("2015-03-02"),new Date("2015-03-03"),new Date("2015-03-04")];

for (let i = 0; i < abc.length-1; i++){
    arr.push(1 + (abc[i+1] - abc[0])/8.64e7);
}

console.log(arr);
RobG
  • 142,382
  • 31
  • 172
  • 209
1

Is this what you want?

abc = [new Date("2015-03-01"),new Date("2015-03-01"),new Date("2015-03-02"),new Date("2015-03-03"),new Date("2015-03-04")];

const result = abc.slice(1).map(date => ~~((date-abc[0]) / (24*60*60*1000)) + 1)

console.log(result)
Loi Nguyen Huynh
  • 8,492
  • 2
  • 29
  • 52