[英]How can I calculate the numbers of month between two dates in C#
I would like to know how to calculate the numbers of Month between two dates. 我想知道如何计算两个日期之间的月数。 Is there any method to calculate it in C#? 有什么方法可以在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
这将导致月份之间的差异:
int months = (Date2.Year - Date1.Year) * 12 + Date2.Month - Date1.Month;
My Noda Time project provides for this: 我的Noda Time项目为此提供了:
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. 有关更多信息,请参见项目文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.