Demonstrating a Function to Get the Last N Months in JavaScript

In many applications, there is often a need to retrieve and display data for a specific number of past months. For example, generating reports, charts, or historical data analysis often requires knowing the months in the recent past. This can be particularly useful in business dashboards, financial applications, or personal tracking systems.

One common requirement is to show the last six months of data, and this can be achieved efficiently using JavaScript. Below, we’ll walk through a simple JavaScript function that retrieves the last six months from a given date.

The Function: getLastSixMonths

The JavaScript function getLastSixMonths takes a date as an input and returns an array of objects representing the last six months, including the full month name, the year, and a formatted string representing the month in month::year format.

Code Explanation:

function getLastSixMonths(date) {
    const yearOrMonthData = [];

    for (let i = 13; i >= 0; i--) {
        // Create a new Date object for the first day of the month (i months ago)
        const lastSixMonth = new Date(date.getFullYear(), date.getMonth() - i, 1);

        // Get the full month name for the current month
        const monthName = lastSixMonth.toLocaleString("default", { month: "long" });

        // Store the month name, year, and formatted string (month::year) in the array
        yearOrMonthData.unshift({
            name: `${monthName} ${lastSixMonth.getFullYear()}`,
            monthOrYear: `${lastSixMonth.getMonth() + 1}::${lastSixMonth.getFullYear()}`
        });
    }

    return yearOrMonthData;
}

// Example usage:
const date = new Date(); // Current date
const monthsData = getLastSixMonths(date);

console.log(monthsData);

Detailed Breakdown:

  1. Function Definition: The getLastSixMonths function accepts a date object as an argument. This allows it to work with any date input, not necessarily the current date.

  2. Looping through Previous Months: The for loop starts at 13 and decrements to 0, which covers the last 14 months (the current month and the previous 13 months). For each iteration, it calculates the date of the first day of the month corresponding to i months ago.

  3. Creating a Date Object: Inside the loop, a new Date object is created for the first day of each month. By using the date.getFullYear() and date.getMonth() - i method, it ensures that the month is correctly calculated, even when crossing over into a new year.

  4. Month Name: The toLocaleString method with the month: "long" option is used to get the full name of the month (e.g., "January", "February").

  5. Storing the Data: Each month’s name, year, and a formatted string in the form of month::year are stored in the yearOrMonthData array.

  6. Unshifting Data: The unshift() method is used to add the data to the front of the array, ensuring that the most recent month is first in the array.

  7. Return the Array: After completing the loop, the function returns the yearOrMonthData array, which contains the last 14 months in the specified format.

Example Output:

For example, if today is January 2025, calling the function getLastSixMonths(new Date()) will return:

[
    { name: "January 2025", monthOrYear: "1::2025" },
    { name: "December 2024", monthOrYear: "12::2024" },
    { name: "November 2024", monthOrYear: "11::2024" },
    { name: "October 2024", monthOrYear: "10::2024" },
    { name: "September 2024", monthOrYear: "9::2024" },
    { name: "August 2024", monthOrYear: "8::2024" },
    { name: "July 2024", monthOrYear: "7::2024" },
    { name: "June 2024", monthOrYear: "6::2024" },
    { name: "May 2024", monthOrYear: "5::2024" },
    { name: "April 2024", monthOrYear: "4::2024" },
    { name: "March 2024", monthOrYear: "3::2024" },
    { name: "February 2024", monthOrYear: "2::2024" },
    { name: "January 2024", monthOrYear: "1::2024" },
    { name: "December 2023", monthOrYear: "12::2023" },
    { name: "November 2023", monthOrYear: "11::2023" }
]

This array provides the last six months' data formatted in a human-readable way.

Practical Use Cases

This function can be extremely useful in various scenarios:

  1. Data Visualization: If you're building a dashboard that needs to display charts or graphs for the last six months of data, you can use this function to generate the relevant months.

  2. Reports: Generating monthly reports often requires pulling data for specific months. This function makes it easy to fetch and format the months correctly.

  3. Tracking Metrics: For applications that track monthly performance metrics (such as sales, website traffic, or user activity), this function can provide a simple way to get the last few months for reporting or analysis.

  4. Dynamic Time Periods: By modifying the loop condition or changing the date input, you can customize this function to retrieve data for any number of past months, not just six.

Conclusion

In conclusion, the getLastSixMonths function is a simple yet powerful way to retrieve and format the last N months of data in JavaScript. Whether you're building a financial application, a business dashboard, or any system that needs to track time-based data, this function will save time and make working with dates much easier. By adjusting the number of months or the date input, you can adapt this function for a variety of use cases, making it highly versatile and useful for developers.

Last updated