How do I get months between two dates in a formula field?

I have a start_date and end_date and I need the number of months from start to end (rounded up) to use in a formula filed

e.g. 2025-03-31 to 2026-05-30 = 14 months

and 2025-03-31 to 2026-06-03 = 15 months

FrancescaS

  • Hi  ,

    If you want the raw calendar months between two dates (e.g. 2025-05-31 to 2025-06-01 returns '1' even though it only represents 1 day and 2025-05-01 to 2025-05-31 returns '0' since it is within the same month), then the following formula achieves that result:

    Fullscreen
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    add(
    multiply(
    subtract(
    year(
    $end_date
    ),
    year(
    $start_date
    )
    ),
    12
    ),
    subtract(
    monthofyear(
    $end_date
    ),
    monthofyear(
    $start_date
    )
    )
    )
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    If you would rather return a result that is representative of the days elapsed (e.g. 2025-05-31 to 2025-06-01 returns '0' since it is only 1 day and 2025-05-01 to 2025-05-31 returns '1' since 30 days rounds up to 1 month), then the follow formula would be better-suited:

    Fullscreen
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    round(
    divide(
    abs(
    subtract(
    daysUntil(
    $end_date
    ),
    daysUntil(
    $start_date
    )
    )
    ),
    30.42
    ),
    0
    )
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    You can also choose to replace round() with floor() or ceil() in the above formula depending on the behavior you want.

    One final note is that if there are scenarios where one or both date fields can be empty, then you will want to put safeguards to only perform these calculations when the date fields are populated. If you don't, your sugarcrm.log file will be littered with errors because the date-based fields will throw errors in the above calculations when it is not a valid date value. You can see an example of how to implement those safeguards in the second formula of a recent post I made.

    Chris

  • Thank you Chris! After seeing that I may opt for an after save logic hook... easier to read! Laughing

  • No problem! I realized that the first formula didn't need to be as complex as I first wrote it, so I simplified that a bit. Good luck with the route you choose. Relaxed