Blues Clues
Blues Clues

Reputation: 1838

Get days using two dates in js

I'm having this trouble where I can only get the days between specified 2 dates. Please see the code below:

var getDaysArray = function(start, end) {
  for (var arr = [], dt = start; dt <= end; dt.setDate(dt.getDate() + 1)) {
    arr.push(new Date(dt));
  }
  return arr;
};

var daylist = getDaysArray(new Date('08/13/2018'), new Date('08/17/2018'));
daylist.map((v) => v.toISOString().slice(0, 10)).join("");
console.log(daylist);

The output of the code above is:

enter image description here

Expected output (due to start and end dates 08/13/2018 and 08/17/2018):

0: Date 2018-08-13T16:00:00.000Z
1: Date 2018-08-14T16:00:00.000Z
2: Date 2018-08-15T16:00:00.000Z
3: Date 2018-08-16T16:00:00.000Z
4: Date 2018-08-17T16:00:00.000Z

Note: The code above was from one of the SO answers found somewhere.

Upvotes: 1

Views: 58

Answers (1)

31piy
31piy

Reputation: 23859

toISOString represents the date in UTC format. You are probably in positive timezone offset, that's why the UTC representation of your date objects are a day off. You can use toLocaleString instead to represent your dates in your timezone.

Another issue is that Array.prototype.map retuns a new array, which you forgot to assign to daylist Without that assignment, no changes in daylist will be made.

Below snippet works as per your requirements.

var getDaysArray = function(start, end) {
  for (var arr = [], dt = start; dt <= end; dt.setDate(dt.getDate() + 1)) {
    arr.push(new Date(dt));
  }
  return arr;
};

var daylist = getDaysArray(new Date('08/13/2018'), new Date('08/17/2018'));
daylist = daylist.map((v) => v.toLocaleString());
console.log(daylist);

Upvotes: 2

Related Questions