3 回答
TA貢獻1856條經驗 獲得超11個贊
您將無法從中獲取價格TimeSpan,因為“月”是可變的計量單位。您必須自己計算它,并且必須弄清楚您希望它如何工作。
例如,要日期喜歡July 5, 2009并August 4, 2009產生一個月或零月區別?如果你說這應該產生一個,然后怎么樣July 31, 2009和August 1, 2009?是那一個月?它僅僅是Month日期值的差異,還是與實際時間跨度更相關?確定所有這些規則的邏輯很重要,因此您必須確定自己的規則并實施適當的算法。
如果您想要的只是月份中的不同(完全不考慮日期值),則可以使用以下方法:
public static int MonthDifference(this DateTime lValue, DateTime rValue)
{
return (lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year);
}
請注意,這將返回一個相對差,這意味著如果rValue大于lValue,則返回值將為負。如果需要絕對差異,可以使用以下方法:
public static int MonthDifference(this DateTime lValue, DateTime rValue)
{
return Math.Abs((lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year));
}
TA貢獻1825條經驗 獲得超4個贊
這是比較痛苦的純.NET做。我建議我自己的Noda Time庫,該庫是專門為以下目的而設計的:
LocalDate start = new LocalDate(2009, 10, 6);
LocalDate end = new LocalDate(2009, 12, 25);
Period period = Period.Between(start, end);
int months = period.Months;
(還有其他選擇,例如,即使您只想數月甚至數年,也可以使用Period period = Period.Between(start, end, PeriodUnits.Months);)
TA貢獻1833條經驗 獲得超4個贊
也許您不想知道月份分數;這段代碼呢?
public static class DateTimeExtensions
{
public static int TotalMonths(this DateTime start, DateTime end)
{
return (start.Year * 12 + start.Month) - (end.Year * 12 + end.Month);
}
}
// Console.WriteLine(
// DateTime.Now.TotalMonths(
// DateTime.Now.AddMonths(-1))); // prints "1"
- 3 回答
- 0 關注
- 862 瀏覽
添加回答
舉報
