get years and months from two dates c# code example
Example 1: compute months c#
public static int GetMonthDifference(DateTime startDate, DateTime endDate)
{
int monthsApart = 12 * (startDate.Year - endDate.Year) + startDate.Month - endDate.Month;
return Math.Abs(monthsApart);
}
Example 2: get list of months and year between two dates c#
public static IEnumerable<(string Month, int Year)> MonthsBetween(
DateTime startDate,
DateTime endDate)
{
DateTime iterator;
DateTime limit;
if (endDate > startDate)
{
iterator = new DateTime(startDate.Year, startDate.Month, 1);
limit = endDate;
}
else
{
iterator = new DateTime(endDate.Year, endDate.Month, 1);
limit = startDate;
}
var dateTimeFormat = CultureInfo.CurrentCulture.DateTimeFormat;
while (iterator <= limit)
{
yield return (
dateTimeFormat.GetMonthName(iterator.Month),
iterator.Year
);
iterator = iterator.AddMonths(1);
}
}