ACF Library

addMonthToDate

Back to List

Description: Add month to date. If startdate's day number is bigger tham the target month, adjust to last day in month.

FileMaker Prototype:

Set Variable [$res; ACF_Run("addMonthToDate"; date_current;  date_startdate;  int_mndcount)]

Category: EXCEL

Function source:

// Add month to date. If startdate's day number is bigger tham the target month, 
// adjust to last day in month. 
function addMonthToDate(date current, date startdate, int mndcount)
    // Extract the day from the start date to ensure consistency when adding months
    int day = string(startdate, "%d"); // Use the start date to handle days near the end of the month properly.
    
    // Extract the current month and year
    int month = string(current, "%m"); 
    int year = string(current, "%Y"); 
    
    // Increment the month by the specified number of months (mndcount)
    month += mndcount; 
    
    // Adjust the year and month if the month exceeds 12
    while (month > 12)
        year++; 
        month = month - 12; 
    end while

    // Initialize the result with the calculated year, month, and original day
    date result;
    result = date(format("%04d-%02d-%02d", year, month, day), "%Y-%m-%d"); 
    
    // Handle invalid dates (e.g., 30th February becomes 2nd March).
    // Trim the day backward until a valid date is found.
    while (int(string(result, "%d")) != day)
        day--; // Decrease the day until the date is valid.
        result = date(format("%04d-%02d-%02d", year, month, day), "%Y-%m-%d"); 
    end while

    // Return the final valid date
    return result; 
end

Back to List