how to get months number between 2 dates in c# code example
Example 1: How to get number of months between 2 dates c#
class Program
{
static void Main(string[] args)
{
DateTime firstDate = new DateTime(2017, 03, 03);
DateTime secondDate =new DateTime(2018, 06, 06);
int months= MonthDiff(firstDate, secondDate);
Console.WriteLine("First Date :"+firstDate);
Console.WriteLine("Second Date :" + secondDate);
Console.WriteLine("Months :"+months);
Console.ReadLine();
}
public static int MonthDiff(DateTime d1, DateTime d2)
{
int m1;
int m2;
if(d1<d2)
{
m1 = (d2.Month - d1.Month);
m2 = (d2.Year - d1.Year) * 12;
}
else
{
m1 = (d1.Month - d2.Month);
m2 = (d1.Year - d2.Year) * 12;
}
return m1 + m2;
}
}
Example 2: convert number of days into months c#
private int ConvertDaysToMonths(double days)
{
const double daysToMonths = 30.4368499;
return Convert.ToInt32(Math.Floor(days / daysToMonths));
}