2

I try to create a list of days between two days.

I created solution like this:

this.daysBetween = [];
while (dateFrom.getDate() !== dateTo.getDate()+1 ) {
    this.daysBetween.push(this.dateFrom);
    dateFrom.setDate(dateFrom.getDate()+1);
  }

But it works only in 90% cases (if there is month change it doesn't work)

e.g. when I pick dates:

dateFrom: 29 august
dateTo: 30 august 

it prints me days from 29 august till 30 september ignoring 31 august ...

Any ideas how to fix my solution, or maybe there is better one?

EDIT:

My question is different than question suggested, because in my question I have as input two dates

e.g.

let dateFrom = new Date(2018, 9, 29);
let dateTo = new Date(2018, 9, 30);

On suggested duplicate result of this could have been int number 1

My question is how to loop through all days between two dates (dateFrom, dateTo)

Where result of those 2 dates examples (dateFrom, dateTo) would've been list with 2 elements:

Mon Oct 29 2018 00:00:00 GMT+0100
Tue Oct 30 2018 00:00:00 GMT+0100 
7
  • 2
    Possible duplicate of How do I get the number of days between two dates in JavaScript? Commented Aug 20, 2018 at 8:17
  • Hello you should have a look to the Date object Commented Aug 20, 2018 at 8:18
  • 1
    @ErikPhilips Nope, I dont want to get number of days. I want to loop through those days and also it's typescript here. Commented Aug 20, 2018 at 8:19
  • 1
    have you tried using moment? Commented Aug 20, 2018 at 8:22
  • 1
    @ErikPhilips edited question with explanation why it isn't a duplicate. Commented Aug 20, 2018 at 8:31

3 Answers 3

6
Simple Typescript Solution is given below

Javascript version on Github

    class MyDate {
        dates: Date[];
        constructor() {
            this.dates = [];
        }

        private addDays(currentDate) { 
                let date = new Date(currentDate);
                date.setDate(date.getDate() + 1);
                return date;
        }

        getDates(startDate: Date, endDate: Date) { 
            let currentDate: Date = startDate;
            while (currentDate <= endDate) { 
                this.dates.push(currentDate);
                currentDate = this.addDays(currentDate);
            }

            return this.dates;
        }
    }

    let md = new MyDate();
    let daysBetween: Date[] = md.getDates(new Date(2018, 7, 22), new Date(2018, 8, 30));
    console.log(daysBetween);
Sign up to request clarification or add additional context in comments.

Comments

6

You could use moment's duration:

/**
 * Get an array of moment instances, each representing a day beween given timestamps.
 * @param {string|Date} from start date 
 * @param {string|Date} to end date
 */
function daysBetween(from, to) {
  const fromDate = moment(new Date(from)).startOf('day');
  const toDate = moment(new Date(to)).endOf('day');

  const span = moment.duration(toDate.diff(fromDate)).asDays();
  const days = [];
  for (let i = 0; i <= span; i++) {
    days.push(moment(fromDate).add(i, 'day').startOf('day'));
  }
  return days;
}

const days = daysBetween('29-Aug-2018', '30-Sep-2018');

console.info(days.map(d => d.toString()).join('\n'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

You can alter the loop start/end condition to include/exclude the first/last day.

Update: Using Luxon instead:

const DateTime = luxon.DateTime;

function daysBetween(start,end){
  dateStart = DateTime.fromJSDate(start);
  dateEnd = DateTime.fromJSDate(end);
  
  diffDays = dateEnd.diff(dateStart,'days');
  const days = [];
  for(let i = 0 ; i < diffDays.days; i++){
    days.push(new Date(dateStart.plus({days:i+1}).toMillis()));
  }
  return days;
}


console.log(daysBetween(new Date('23-Feb-2020'),new Date('5-Mar-2020')));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.min.js"></script>

1 Comment

Yeah, thats what I was looking for, thanks for your time :)
5

You could calculate the difference in milliseconds, and then convert that into the difference in days.

You can then use this to fill an array with Date objects:

const MS_PER_DAY: number = 1000 x 60 x 60 x 24;
const start: number = dateFrom.getTime();
const end: number = dateTo.getTime();
const daysBetweenDates: number = Math.ceil((end - start) / MS_PER_DAY);

// The days array will contain a Date object for each day between dates (inclusive)
const days: Date[] = Array.from(new Array(daysBetweenDates + 1), 
    (v, i) => new Date(start + (i * MS_PER_DAY)));

4 Comments

That isn’t what the OP wants.
I want to create the list of days, so your solution doesn't help. (Also your solution ignores last day, so given start (2018, 11, 8), end (2018, 11, 9) will loop only once, but you have here 2 days...
Yeah, thats what I was looking for, thanks :) I need to think right now which solution I should use. Your or S.D. and than I'll accept the answer. Anyway really thank for your time :)
If you fancied accepting this because it's the most concise, and doesn't require an external library, you could!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.