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.
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));
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…