Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to show only date 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/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');

alert(getDatesInRange(d1, d2).map(date => date.toDateString()));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading