Quantcast
Channel: Difference in months between two dates - Stack Overflow
Viewing all articles
Browse latest Browse all 48

Answer by Dan Hilderbrand for Difference in months between two dates

$
0
0

I was working on a project that only delt in years and months. Here is a solution that may help.

/// <summary>/// Get the total months between two date.  This will count whole months and not care about the day./// </summary>/// <param name="firstDate">First date.</param>/// <param name="lastDate">Last date.</param>/// <returns>Number of month apart.</returns>private static int GetTotalMonths(DateOnly firstDate, DateOnly lastDate){    int yearsAppart = lastDate.Year - firstDate.Year;    int monthsAppart = lastDate.Month - firstDate.Month;    return (yearsAppart * 12) + monthsAppart;}private static int GetTotalMonths(DateTime firstDate, DateTime lastDate){    return GetTotalMonths(DateOnly.FromDateTime(firstDate), DateOnly.FromDateTime(lastDate));}

Viewing all articles
Browse latest Browse all 48

Trending Articles