-2

I wrote this for loop:

// I expect to get the day of 10/12/2019
const startDate = parseInt(new Date('10/12/2019').getDate());

// I expect to get the day of 22/12/2019
const endDate = parseInt(new Date('22/12/2019').getDate());

// Creating an empty array to push data later on
let freedays = [];

// for loop where i equals the day of the startdate: '10', and where the condition is that 
let i has to be smaller of equal to endDate: '22' for the loop to stop.
for (let i = startDate; i <= endDate; i++) {
        freedays.push(i)
      }

console.log(freedays)

I always get an empty array when executing this function, whereas I want to get the days in between startDate and EndDate.

Could anyone help me understand what I'm doing wrong?

2 Answers2

0

You are using the wrong date format. It is expecting mm/dd/yyyy but you are giving it dd/mm/yyyy. The 22 for the month gives error and makes endDate NaN

const startDate = parseInt(new Date('12/10/2019').getDate());
const endDate = parseInt(new Date('12/22/2019').getDate());
let freedays = [];
for (let i = startDate; i <= endDate; i++) {
        freedays.push(i)
      }
console.log(freedays)
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

First of all, welcome to StackOverflow!

Secondly ... There's a bit of misunderstanding in your code, and you really need to re-think what you are doing, as it works fine if 2 dates have the same month and year :)

first of all, try debug things:

  • open console in any browser (F12 on windows) and write new Date('22/12/2019').getDate() and see what happens
  • you will find out that it returns NaN (Not a Number)
  • why parsing an already number into a number?
  • a bigger idea, is to write code in a UI so you can debug it line by line ... learning this will start improving your code and the way you find your own mistakes

Now, talking about code ...

If this is for learning proposes: great, if not, no need to re-invent the wheel, momentJs and DateFns already have such functions

using momentJs

var moment = require('moment');
var d = moment("12-22-2019").diff(moment("12-10-2019"), "days");
// 12

using DateFns

var differenceInDays = require('date-fns/differenceInDays');
var d = differenceInDays(new Date("12-22-2019"), new Date("12-10-2019"));
// 12

if is only for testing proposes:

  • you would be better off by using the Date object itself and not a part of it, so you no longer bound to the same month and year
  • remember to, soon you have the difference between 2 dates, convert it to the unit you want (seconds, days, etc)

all this is better answered in this question

balexandre
  • 73,608
  • 45
  • 233
  • 342