Home > Net >  Get all Dates between 2 Dates Javascript
Get all Dates between 2 Dates Javascript

Time:03-23

I'm having trouble with a feature that's supposed to bring up dates between two dates

I have identified the error and it depends on the time of the start date.

function getDatesInRange(startDate, endDate) {
 const date = new Date(startDate.getTime());

 const dates = [];

 while (date <= endDate) {
  dates.push(new Date(date));
  date.setDate(date.getDate()   1);
 }

 return dates;
}

const d1 = new Date(doc.travel_start);
const d2 = new Date(doc.travel_end);

getDatesInRange(d1, d2)

travel_end: "2022-03-23T20:00:57.118Z" travel_start: "2022-03-20T05:59:57.118Z",

Correct output: [ 2022-03-20T05:59:57.118Z, 2022-03-21T05:59:57.118Z, 2022-03-22T05:59:57.118Z, 2022-03-23T05:59:57.118Z ]

If i change the timestamp of travel_start to hour 23 the last date of my array is missing [ 2022-03-20T21:59:57.118Z, 2022-03-21T21:59:57.118Z, 2022-03-22T21:59:57.118Z ]

I have tried to remove the timestamp from travel_start by .setHours(0,0,0,0) without success.

CodePudding user response:

you are on the right way

setHours could have an issue with timezone try to use setUTCHours;

and reset start and end dates before any calculations

try out:

function getDatesInRange(startDate, endDate) {
    const start = new Date(new Date(startDate).setUTCHours(0, 0, 0, 0));
    const end = new Date(new Date(endDate).setUTCHours(0, 0, 0, 0));
    
 const date = new Date(start.getTime());

 const dates = [];

 while (date <= end) {
  dates.push(new Date(date));
  date.setDate(date.getDate()   1);
 }

 return dates;
}

const travel_start = "2022-03-20T05:59:57.118Z";
const travel_start2  ="2022-03-20T23:59:57.118Z";

const travel_end = "2022-03-23T20:00:57.118Z"; 

const res1 = getDatesInRange(travel_start, travel_end);
const res2 = getDatesInRange(travel_start2,travel_end);

console.log('res1', res1)
console.log('res2', res2)

CodePudding user response:

If you're not opposed to using external libraries, date-fns has a lot of useful functionality, including what you are looking to do.

example:

import { eachDayOfInterval } from "date-fns";

function getDatesInRange(startDate, endDate) {
    return eachDayOfInterval({
        start: new Date(startDate),
        end: new Date(endDate)
    })
} 

getDatesInRange(d1, d2)

Otherwise, shutsman's answer seems to make sense.

  • Related