There is no “diff method” for months in TimeSpan Class.
So you must calulate months difference and years difference one by one
The following code will calculate months between two dates:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Program { static void Main(string[] args) { //First Date DateTime firstDate = new DateTime(2017, 12, 01); //Second Date DateTime secondDate =new DateTime(2018, 04, 01); //DateTime.Now; int m1 = (secondDate.Month - firstDate.Month);//for years int m2 = (secondDate.Year - firstDate.Year) * 12; //for months int months = m1 + m2; Console.WriteLine("First Date :"+firstDate); Console.WriteLine("Second Date :" + secondDate); Console.WriteLine("Months :"+months); Console.ReadLine(); } } |
Calculate the number of months between two dates using Static Method with C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | class Program { static void Main(string[] args) { //First Date DateTime firstDate = new DateTime(2017, 03, 03); //Second Date DateTime secondDate =new DateTime(2018, 06, 06); //DateTime.Now; 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);//for years m2 = (d2.Year - d1.Year) * 12; //for months } else { m1 = (d1.Month - d2.Month);//for years m2 = (d1.Year - d2.Year) * 12; //for months } return m1 + m2; } } |
Output: