Skip to content

Instantly share code, notes, and snippets.

@gramcha
Last active April 21, 2020 10:19
Show Gist options
  • Save gramcha/08a636abfd41f24e99648e9ef210a7d4 to your computer and use it in GitHub Desktop.
Save gramcha/08a636abfd41f24e99648e9ef210a7d4 to your computer and use it in GitHub Desktop.
getMonthWiseIntervalDatesFromADateRange
const moment = require('moment');
function getMonthWiseIntervalDatesFromADateRange(startDateString, endDateString) {
let startMoment = moment(startDateString);
const endMoment = moment(endDateString);
const monthDiff = endMoment.diff(startMoment, 'months');
console.log(monthDiff);
const pairsOfDates = [];
if (monthDiff === 0) {
const result = { startDate: startMoment, endDate: moment(endMoment) };
result.startDate = result.startDate.toDate();
result.endDate = result.endDate.toDate();
pairsOfDates.push(result);
} else {
for (let i = 0; i <= monthDiff; i += 1) {
const result = { startDate: startMoment, endDate: moment(startMoment).endOf('months') };
startMoment = moment(result.endDate).add(1, 'milliseconds');
result.startDate = result.startDate.toDate();
result.endDate = result.endDate.toDate();
pairsOfDates.push(result);
}
if (pairsOfDates.length) {
pairsOfDates[pairsOfDates.length - 1].endDate = endMoment.toDate();
}
}
return pairsOfDates;
}
const pairsOfDates = getMonthWiseIntervalDatesFromADateRange('2019-05-21T11:09:50.340', (new Date()).toISOString());
console.log('pairsOfDates - ', pairsOfDates);
// const pairsOfDates = getMonthWiseIntervalDatesFromADateRange('2020-01-22T18:30:00.000Z', '2020-02-25T18:29:59.999Z');
// console.log('pairsOfDates - ', pairsOfDates);
let date = new Date();
console.log(date.toString().replace(/\w+ (\w+) (\d+) (\d+).*/, '$2-$1-$3'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment