Microsoft Dynamics 365 Calculate Months Between Two Dates

Introduction

Date calculations are among the most common requirements in Microsoft Dynamics 365 CRM and Dataverse solutions. Businesses often need to determine the number of months between two dates for contracts, subscriptions, warranties, employee tenure, project schedules, and service agreements.

Business Scenario

Consider a Contract Management application with the following fields: Contract Start Date, Contract End Date, and Requirement: Calculate Contract Duration in Months. For example, Start Date: 01-Jan-2025, End Date: 01-Jul-2025, Result: 6 Months.

Common Use Cases

Method 1: Using JavaScript in Dynamics 365

Assume the following fields exist: new_startdate, new_enddate, new_months. JavaScript function: calculateMonths(executionContext) {...}

Method 2: Using Power Automate

Trigger: When Row Is Added or Modified. Fields: Start Date, End Date. Expression: sub(add(mul(sub(int(formatDateTime(outputs('EndDate'), 'yyyy')), int(formatDateTime(outputs('StartDate'), 'yyyy'))), 12), int(formatDateTime(outputs('EndDate'), 'MM'))), int(formatDateTime(outputs('StartDate'), 'MM')))

Method 3: Using Calculated Column

Create: Duration (Months). Formula: EndDate - StartDate. Although calculated columns typically return values in days, additional business logic can be applied to convert those values into months.

Method 4: Using Power Apps Formula

Canvas App Formula: DateDiff(StartDatePicker.SelectedDate, EndDatePicker.SelectedDate, TimeUnit.Months). Example: Start Date: 01-Jan-2025, End Date: 01-Aug-2025, Result: 7 Months.

Method 5: Using Plugin (C#)

Plugin Code: DateTimestartDate = (DateTime)entity['new_startdate']; DateTimeendDate = (DateTime)entity['new_enddate']; int months = ((endDate.Year - startDate.Year) * 12) + endDate.Month - startDate.Month; entity['new_months'] = months;

Real-World Example

Employee Experience: Fields: Joining Date, Current Date. Values: 01-Jan-2022, 01-Jan-2025, Result: 36 Months.

Comparing Different Methods

MethodDifficultyPerformance
JavaScriptMediumHigh
Power AutomateEasyMedium
PluginAdvancedVery High
Power Apps FormulaEasyHigh
Calculated ColumnEasyMedium

Best Practices

Benefits