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

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

问题描述

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

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

在 C# 中是否有等效于 VB 的 DateDiff() 方法.我需要找出相隔数年的两个日期之间的月数差异.文档说我可以使用 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 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天全站免登陆