Skip to main content

📆 How to Get the Start and End Date of the Previous Quarter in Apex ?

 When working with Salesforce data, it's often necessary to filter or report on records from a specific quarter. If you're looking to retrieve the start and end dates of the previous quarter based on the current date, here’s a simple and reusable Apex utility you can use.

🔧 Apex Utility Methods

Below are two helper methods:

  1. getStartDate() — Calculates the start date of the previous quarter.

  2. getEndDate() — Calculates the end date of the previous quarter, based on the start date.

// Helper method to get the start date of the previous quarter
private Date getStartDate() {
    Date today = Date.today();

    Integer currentYear = today.year();
    Integer currentMonth = today.month();

    // Determine the first month of the previous quarter
    Integer previousQuarterStartMonth = ((currentMonth - 1) / 3) * 3 + 1 - 3;

    // Adjust the year if the previous quarter falls in the previous year
    if (previousQuarterStartMonth <= 0) {
        previousQuarterStartMonth += 12;
        currentYear--;
    }

    // Return the first day of the previous quarter
    return Date.newInstance(currentYear, previousQuarterStartMonth, 1);
}

// Helper method to get the end date of the previous quarter
private Date getEndDate() {
    Date previousQuarterStartDate = getStartDate();
    // Add 3 months and subtract 1 day to get the last day of the quarter
    return previousQuarterStartDate.addMonths(3).addDays(-1);
}

🧠 Explanation

  • The start month of the current quarter is calculated using: 

((currentMonth - 1) / 3) * 3 + 1

  • Then we subtract 3 to move to the previous quarter.

  • We adjust for year boundaries (e.g., if today is in Q1, the previous quarter is in the previous year).

  • The end date is simply 3 months after the start, minus one day

✅ Example

If today's date is April 25, 2025, then:

getStartDate() will return January 1, 2025

  • getEndDate() will return March 31, 2025

Comments