What is the easiest way to get the difference between months between two dates in C #?

What is the easiest way to get the difference between months between two dates in C #?

ie: (date1 - date2) .TotalMonths .. kind of thing. thank!

+3
source share
5 answers

Given the updates you made to your original question: how about writing a function that takes two dates and does the following,

DateTime d1 = new DateTime(2008, 12, 1);
DateTime d2 = new DateTime(2009, 1, 1);

var month_diff = (d2.Year - d1.Year)*12 + (d2.Month - d1.Month);
Console.WriteLine(month_diff);
+5
source

Since you already know that your dates will be first per month:

int totalMonths = (date2.Year - date1.Year)*12 + date2.Month - date1.Month;
+4
source

, , , , . - :

DateTime dt1 = new DateTime( 2010, 10, 23);
DateTime dt2 = new DateTime( 2010, 7, 23);
TimeSpan ts = dt1 - dt2;
int days_per_month = 30;
Console.Write( ts.TotalDays / days_per_month);

- 2010 Feb 1 - 2010 Jan 31, 1 , , , ,

Console.Write( dt1.Month - dt2.Month);

, , .:)

+2
source

If you do not know how to calculate the date range in .net, here is a good example:

DateTime startTime = DateTime.Now;
DateTime endTime = DateTime.Now.AddSeconds(75);

TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
Console.WriteLine( "Time Difference (hours): " + span.Hours );
Console.WriteLine( "Time Difference (days): " + span.Days );

Source: here .

DateTime does not disclose the difference in the month, since each month has a different number of days. The easiest way to get a month is totaldays / 30.

+2
source

TimeSpan Class :)

 TimeSpan span = endTime.Subtract ( startTime );
 Console.WriteLine( "Time Difference (months): " + span.Days / 30 );
0
source

Source: https://habr.com/ru/post/1732126/


All Articles