0

Currently i'm importing Moment and Moment range as below, Need the array of dates between given 2 dates so that dates can be iterated

import Moment from 'moment';
import {extendMoment} from 'moment-range';

import React, {Component} from 'react';

class T extends Component {
  constructor(props) {
    const start = moment("2018-10-14", 'YYYY-MM-DD');
    const end = moment("2018-10-20", 'YYYY-MM-DD');
    const range = moment.range(start, end);
    //need an array of dates in'YYYY-MM-DD' to itarate
  }
}
1
  • Take a look at moment-range's by that Iterate over your range by a given period. Commented Oct 23, 2018 at 8:13

2 Answers 2

1

You can clone the start date and add one day at a time, pushing a formatted date to an array.

By using a while loop and isBefore you can ensure you keep iterating until you're at the end date.

You might want to make sure this behaves correctly at the boundaries of your start and end. I.e.: do you want it to include or exclude the input days?

const start = moment("2018-10-14", 'YYYY-MM-DD');
const end = moment("2018-10-20", 'YYYY-MM-DD');

const current = start.clone();
const result = [];

while (current.isBefore(end)) {
  result.push(current.format("YYYY-MM-DD"));
  current.add(1, "day");
}

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

0

To do what you are asking since you already have moment-range you would do something like this:

const range = moment.range(moment("2018-10-14"), moment("2018-10-20"));

console.log(Array.from(range.by('day')).map(x => x.format('YYYY-MM-DD')))

If you do not need to format right away it would simply be:

Array.from(range.by('day'))  // for your range

Here is an example in node but it would be similar in your case just import by

Comments

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.