0

I have two days.(start and end days) How can I get the year and month between the two days?

For example: start day: Wed Jun 01 2016 00:00:00 GMT+0900 (JST) end day : Sat Apr 01 2017 00:00:00 GMT+0900 (JST)

result :['06/2016','07/2016','08/2016','09/2016','10/2016','11/2016','12/2016','01/2017','02/2017','03/2017','04/2017']

Tomomi
  • 67
  • 1
  • 1
  • 8
  • 1
    Try with moment.js – Yogen Darji Jul 22 '17 at 02:24
  • Maybe parse the strings to dates, step through the dates and generate a formatted string for each. You could also do the same without using a Date by applying appropriate logic manually. There are plenty of questions on parsing and formatting here already ([*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results), [*Where can I find documentation on formatting a date in JavaScript?*](https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript)) What have you tried? – RobG Jul 22 '17 at 02:33

1 Answers1

1

Using the moment.js library:

function getDates(startDate, stopDate) {
        var dateArray = [];
        var currentDate = moment(startDate);
        var stopDate = moment(stopDate);
        while (currentDate <= stopDate) {
            dateArray.push( moment(currentDate).format('YYYY-MM-DD') )
            currentDate = moment(currentDate).add(1, 'days');
        }
        return dateArray;
    }

Remember to change the format to use according to your date format.


If you can't (or don't want to) use the momentjs library, you can do something like:

var start = new Date("Wed Jun 01 2016 00:00:00"),
    end = new Date("Sat Apr 01 2017 00:00:00"),
    currentDate = new Date(start.getTime()),
    between = [];

while (currentDate <= end) {
    between.push(new Date(currentDate));
    currentDate.setDate(currentDate.getDate() + 1);
}
andreybleme
  • 689
  • 9
  • 23
  • 1
    I changed the format 'YYYY-MM' and added 'if' since I want to get only different month records. Then I could get the result I wanted. Thank you very much! while (currentDate <= stopDate) { var tempDay = moment(currentDate).format('YYYY-MM'); if(dateArray[dateArray.length-1] != tempDay){ dateArray.push(tempDay) } currentDate = moment(currentDate).add(1, 'days'); } – Tomomi Jul 22 '17 at 03:06