DateTime差异恢复正确的月份甚至几年? [英] DateTime difference returing correct no of months and or even years?
问题描述
谢谢
看看 Noda时间。它并不是一般的生产准备,但相关的位可能适用于您当前的要求:)
请注意, TimeSpan
将不做你想要的,因为1个月可能意味着不同的天数取决于月份,而$ code> TimeSpan 不锚定。
在Noda时间,您需要一个期间
。例如:
LocalDate start = new LocalDate(2010,4,15);
LocalDate end = new LocalDate(2010,6,19);
期间= Period.Between(开始,结束); //默认为年/月/日
Console.WriteLine(period.Months); // 2
Console.WriteLine(period.Days); // 4
请注意,日期/时间算术很难 ...在某些情况下正确的答案不太明显。
Is there any built-in function how can I get the difference between tho DateTime objects in better way than just number of days? I mean something like 1 month, 23 days. I find it pretty hard to calculate due to differnet number of days in each month, leap years etc. Thanks
Have a look at Noda Time. It's not production-ready in general yet, but the relevant bits may work well enough for your current requirements :)
Note that TimeSpan
will not do what you want, because "1 month" can mean a different number of days depending on the month, and a TimeSpan
isn't anchored.
In Noda Time, you want a Period
. For example:
LocalDate start = new LocalDate(2010, 4, 15);
LocalDate end = new LocalDate(2010, 6, 19);
Period period = Period.Between(start, end); // Defaults to Year/Month/Day
Console.WriteLine(period.Months); // 2
Console.WriteLine(period.Days); // 4
Note that date/time arithmetic is hard... in some cases "the right answer" isn't at all obvious.
这篇关于DateTime差异恢复正确的月份甚至几年?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!