两个日期之间的月份差异 [英] Difference in months between two dates

查看:120
本文介绍了两个日期之间的月份差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算C#中两个日期之间的差异?

How to calculate the difference in months between two dates in C#?

有相当于VB的 DateDiff()方法在C#中。我需要在两个日期之间的月份中找到差异。文档说我可以使用 TimeSpan ,如下所示:

Is there is equivalent of VB's DateDiff() method in C#. I need to find difference in months between two dates that are years apart. The documentation says that I can use TimeSpan like:

TimeSpan ts = date1 - date2;

但这给了我几天的数据。 我不想将这个数字除以30 ,因为不是每个月都是30天,而且由于两个操作数的值相互分开,所以恐怕除以30可能会给我错误的价值

but this gives me data in Days. I don't want to divide this number by 30 because not every month is 30 days and since the two operand values are quite apart from each other, I am afraid dividing by 30 might give me a wrong value.

任何建议?

推荐答案

假设一个月的日子是不相关的(即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.

这篇关于两个日期之间的月份差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆