Home > Software design >  Get the months between two dates JavaScript
Get the months between two dates JavaScript

Time:12-03

Problem

First off, I am going to clarify that this question is not a duplicate of Difference in months between two dates in javascript or javascript month difference

My question is specifically about getting the months in between two dates, not the number of months.

Expected Results

So If date1 is 11/01/2022 (mm/dd/yyyy) and date2 is 02/20/2023, it should output an array of months including the month of date1 and date2 like ["November", "December", "January", "February"]. I need to know how to return the actual months between two dates, not the number of months. Can somebody explain what would be the way to do that?

CodePudding user response:

The post linked in the question is already a good start.

Maybe think about how you would do it when you want to write the results to a sheet of paper.

When we know the month to start, as an index [0...11], we can count from there and add the month names from an array:

const xmas = new Date("December 25, 1999 23:15:30");
const summer = new Date("June 21, 2003 23:15:30");

function monthsBetween(dstart, dend) {
    const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    let result = [];
    let current = dstart.getMonth();
    let end = (dend.getFullYear() - dstart.getFullYear()) * 12   dend.getMonth();
    for (;current <= end; current  = 1) {
        result.push(monthNames[current % 12]);
    }
    return result;
}

console.log(monthsBetween(xmas, summer)); // [December, January, February..., December, January, ...., June (multiple years)
console.log(monthsBetween(xmas, xmas)); // ["December"]

In your example 2022-11-01 to 2023-02-20, current would count from 10 (November, indexed from 0) to 13 (1: February indexed from 0 1 year = 12 months difference)

  • Related