I want to get a list of all the months that exists between the 2 dates in JS. For ex:
'2021-04-25' to '2021-05-12' should return [4,5] // case when num difference between dates is less than 30 days
'2021-04-25' to '2021-08-12' should return [4,5,6,7,8]
'2021-10-25' to '2022-02-12' should return [10,11,12,1,2]
The following code works but doesn't give the right result for '2021-04-25' to '2021-05-12'. it returns only [4]
I tried examples here JavaScript: get all months between two dates? but momentjs not giving endMonth if days <30
On the momentjs site they say: "We now generally consider Moment to be a legacy project in maintenance mode. It is not dead, but it is indeed done." You can use another library as the end-date.
Here is an example with the same logic proposed by AlTheLazyMonkey with date-fns
import {
addMonths,
getMonth,
isBefore,
isEqual,
startOfMonth
} from "date-fns";
let start = "2021-06-15";
let end = "2021-12-26";
const isSameOrBefore = (start, end) => {
const result = (isBefore(start, end) || isEqual(start, end)) ?
true :
false
return result
};
const getArrayOfMonths = (start, end) => {
let startDate = startOfMonth(new Date(start));
let endDate = startOfMonth(new Date(end));
const arrayOfMonths = [];
if (isBefore(endDate, startDate)) {
console.log("End date must be greated than start date.");
}
while (isSameOrBefore(startDate, endDate)) {
arrayOfMonths.push(getMonth(startDate) + 1);
startDate = addMonths(startDate, 1);
}
return arrayOfMonths;
};
console.log(getArrayOfMonths(start, end));
console.log(getArrayOfMonths("2021-02-15", "2021-9-15"));
I think this is a good solution for get the results that you are looking for
function getMonths(start, end) {
start = moment(start).startOf('month');
end = moment(end).startOf('month');
if (start.isAfter(end))[start, end] = [end, start]; // This is only for order the dates
const months = [];
while (start.isSameOrBefore(end)) {
months.push(start.month() + 1);
start.add(1, 'months');
}
return months;
}
console.log(getMonths('2021-04-25', '2021-05-12'));
console.log(getMonths('2021-04-25', '2021-08-12'));
console.log(getMonths('2021-10-25', '2022-02-12'));
console.log(getMonths('2021-04-25', '2022-02-12'));
console.log(getMonths('2021-06-26', '2020-02-12'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>