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

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

问题描述

如何计算差异月两个日期之间在C#?

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

时有相当于VB的则DateDiff在C#()方法。我需要找到差异月两个日期是相隔多年间。该文件说,我可以使用时间跨度这样的:

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),与日期1> 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.

更新(与感谢加里

如果使用的平均月的方法,稍微更准确的数目要用于'每年的天数平均是 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天全站免登陆