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

Javascript: Get all dates between from and to dates

I am using the following in a ReactJS app:

var getDaysArray = function(s, e) {
  for (var a = [], d = new Date(s); d <= e; d.setDate(d.getDate() + 1)) {
    a.push(new Date(d));
  }
  return a;
};

const abc = new Date(item.DateTo.toDate()).toISOString().substring(0, 10);
const def = new Date(item.DateFrom.toDate()).toISOString().substring(0, 10);

var daylist = getDaysArray(def, abc);

The DateTo and DateFrom are stored as a firebase timestamp – so am converting this and both abc and def return correct (in console.log) = 2022-05-25 and 2022-05-31 so wondering why this is not working?

daylist always returns an empty array []

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

>Solution :

The problem here came from the fact you were transforming your dates into
String using the following command : new Date(item.DateTo.toDate()).toISOString().substring(0, 10);

Then you were comparing a string and a date object in your for loop with d <= e

To work with date in JS, you should let them as date as much as possible

const item = {
  DateTo: 1653462937961,
  DateFrom: 1652997600000,
}

const getDaysArray = function(s, e) {
  const a = []
  for (let d = new Date(s); d <= e; d.setDate(d.getDate() + 1)) {
    a.push(new Date(d));
  }
  return a;
};

const abc = new Date(item.DateTo)
const def = new Date(item.DateFrom)

var daylist = getDaysArray(def, abc);
console.log(daylist)

Note : Try to avoid use var and rather use const

and as @Louys Patrice Bessette mentioned, you should use meaningful variable names.

For example use startDate instead of s or even dates instead of a

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