计算两个日期之间的月差 [英] calculating the difference in months between two dates

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

问题描述

在C#/。NET 时间跨度 TotalDays TotalMinutes 等,但我想不出总个月差的公式。每月闰年可变天一直扔我。我怎样才能获得的 TotalMonths

In C#/.NET TimeSpan has TotalDays, TotalMinutes, etc. but I can't figure out a formula for total months difference. Variable days per month and leap years keep throwing me off. How can I get TotalMonths?

修改对不起,不是更清楚:我知道我能不能真正得到这个从时间跨度,但我想用 TotalDays TotalMinutes 将是一个很好的例子,前preSS什么,我一直在寻找......除了我试图获得总个月。

Edit Sorry for not being more clear: I know I can't actually get this from TimeSpan but I thought using TotalDays and TotalMinutes would be a good example to express what I was looking for ... except I'm trying to get Total Months.

例如:2009年12月25日 - 2009年10月6日= 2 TotalMonths。 10月6号至11月5日等于0个月。 11月6日,1个月。在12月6日,1月

Example: Dec 25, 2009 - Oct 6, 2009 = 2 TotalMonths. Oct 6th to Nov 5th equals 0 months. On Nov 6th, 1 month. On Dec 6th, 2 months

推荐答案

您将无法获得从一个时间跨度,因为月是测量变量单位。你必须自己进行计算,你就必须找出你想要如何准确它的工作。

You won't be able to get that from a TimeSpan, because a "month" is a variable unit of measure. You'll have to calculate it yourself, and you'll have to figure out how exactly you want it to work.

例如,应该日期如 2009年7月5日 2009年8月4 产生一个月或零个月差分?如果你说这应该产生一个,那么怎么样 2009年7月31日 2009年8月1日?是的的一个月?它是的值仅仅为日期的差别,还是更多地涉及的时间跨度实际?确定所有这些规则的逻辑是不平凡的,所以你必须确定你自己的,并执行相应的算法。

For example, should dates like July 5, 2009 and August 4, 2009 yield one month or zero months difference? If you say it should yield one, then what about July 31, 2009 and August 1, 2009? Is that a month? Is it simply the difference of the Month values for the dates, or is it more related to an actual span of time? The logic for determining all of these rules is non-trivial, so you'll have to determine your own and implement the appropriate algorithm.

如果你想要的是简单地在几个月的差别 - 完全无视日期值 - 那么你可以使用这样的:

If all you want is simply a difference in the months--completely disregarding the date values--then you can use this:

public static int MonthDifference(this DateTime lValue, DateTime rValue)
{
    return (lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year);
}

请注意,这将返回一个相对差,这意味着如果右值是大于左值,则返回值将是负的。如果你想要一个绝对的区别,你可以这样做:

Note that this returns a relative difference, meaning that if rValue is greater than lValue, then the return value will be negative. If you want an absolute difference, you can use this:

public static int MonthDifference(this DateTime lValue, DateTime rValue)
{
    return Math.Abs((lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year));
}

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

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