Difference in months between two dates

前端 未结 30 1239
天命终不由人
天命终不由人 2020-11-22 11:02

How to calculate the difference in months between two dates in C#?

Is there is equivalent of VB\'s DateDiff() method in C#. I need to find difference in

30条回答
  •  失恋的感觉
    2020-11-22 11:38

    Here is my contribution to get difference in Months that I've found to be accurate:

    namespace System
    {
         public static class DateTimeExtensions
         {
             public static Int32 DiffMonths( this DateTime start, DateTime end )
             {
                 Int32 months = 0;
                 DateTime tmp = start;
    
                 while ( tmp < end )
                 {
                     months++;
                     tmp = tmp.AddMonths( 1 );
                 }
    
                 return months;
            }
        }
    }
    

    Usage:

    Int32 months = DateTime.Now.DiffMonths( DateTime.Now.AddYears( 5 ) );
    

    You can create another method called DiffYears and apply exactly the same logic as above and AddYears instead of AddMonths in the while loop.

提交回复
热议问题