12

2つの日付の間の月の数を計算する方法を知りたいです。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
4

2 に答える 2

14

これにより、月間の違いが得られます。

int months = (Date2.Year - Date1.Year) * 12 + Date2.Month - Date1.Month;
于 2012-05-31T08:20:48.897 に答える
9

私の野田時間プロジェクトはこれを提供します:

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

詳細については、算術のプロジェクト ドキュメントを参照してください。

于 2012-05-31T08:17:45.100 に答える