Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate the numbers of month between two dates in C#

Tags:

c#

asp.net

I would like to know how to calculate the numbers of Month between two dates. Is there any method to calculate it in C#?

Eg1.    Date1 = "2011/11/01"  
        Date2 = "2012/02/01"     
Result. Numbers of Month =3  

 Eg2.  Date1 = "2012/01/31"
       Date2 = "2012/02/01"  
Result. Numbers of Month =1

 Eg3.  Date1 = "2012/01/01"  
       Date2 = "2012/02/28"
 Result. Numbers of Month =1
like image 589
lelewin Avatar asked May 31 '12 08:05

lelewin


2 Answers

This will give difference between months:

int months = (Date2.Year - Date1.Year) * 12 + Date2.Month - Date1.Month;
like image 186
Tschareck Avatar answered Oct 04 '22 19:10

Tschareck


My Noda Time project provides for this:

LocalDate date1 = new LocalDate(2011, 11, 1);
LocalDate date2 = new LocalDate(2012, 2, 1);
Period period = Period.Between(date1, date2, PeriodUnits.Months);
long months = period.Months; // 3

See the project documentation for arithmetic for more information.

like image 9
Jon Skeet Avatar answered Oct 05 '22 19:10

Jon Skeet