Search code examples
javascriptdatetimedate-range

How to show dates between 2 dates without time Js


So I have this code that gives me the dates between date A and date B, but it also shows the time which I dont want.

This is my current code that works:

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("2022-01-18");
const d2 = new Date("2022-01-24");

console.log(getDatesInRange(d1, d2));

I saw online even here that some say to use

return dates.split(" ")[0];

But it still returns the time.

How can I return only the date (year, month, day) and not time?


Solution

  • You can use .toDateString():

    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('2022-01-18');
    const d2 = new Date('2022-01-24');
    
    console.log(getDatesInRange(d1, d2).map(date => date.toDateString()));
    

    Which will get the date, map it to find only the "date" (not time) and console.log it.