如何计算C#中两个日期之间的月份数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10829732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:26:13  来源:igfitidea点击:

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

c#asp.net

提问by lelewin

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

采纳答案by Tschareck

This will give difference between months:

这将导致月份之间的差异:

int months = (Date2.Year - Date1.Year) * 12 + Date2.Month - Date1.Month;

回答by Jon Skeet

My Noda Timeproject 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 arithmeticfor more information.

有关更多信息,请参阅算术项目文档