且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

两个日期之间的月份差异

更新时间:2023-01-30 10:01:09

假设一个月的日子是不相关的(即2011.1.1和2010.12.31之间的差异为1),date1> date2为正值,date2> date1为负值

Assuming the day of the month is irrelevant (i.e. the diff between 2011.1.1 and 2010.12.31 is 1), with date1 > date2 giving a positive value and date2 > date1 a negative value

((date1.Year - date2.Year) * 12) + date1.Month - date2.Month

或者,假设您想要在两个日期之间大概数字平均月份,以下内容应适用于所有但非常巨大的日期差异。

Or, assuming you want an approximate number of 'average months' between the two dates, the following should work for all but very huge date differences.

date1.Subtract(date2).Days / (365.25 / 12)

请注意,如果您要使用后一种解决方案,那么您的单元测试应说明应用程序设计的最广泛的日期范围编辑以相应地处理和验证计算结果。

Note, if you were to use the latter solution then your unit tests should state the widest date range for which your application is designed to work with and validate the results of the calculation accordingly.

更新(感谢 Gary

如果使用平均月份方法,平均每年天数使用的稍微准确的数字是 365.2425

If using the 'average months' method, a slightly more accurate number to use for the 'average number of days per year' is 365.2425.