如何准确地得到两个DateTime对象之间的差异"十年" [关闭,使用NodaTime] [英] How to accurately get difference between two DateTime object in "Years" [Closed, use NodaTime]
问题描述
如何准确地获得十年两个的DateTime
对象之间的差异(年)?
How to accurately get difference(in years) between two DateTime
objects in "Years"?
DateTime.Subtract()
给出时间跨度
的差异,最大面额为天。
DateTime.Subtract()
gives difference in TimeSpan
and the maximum denomination is Days.
所以,如果我想获得准确的,如今,一天之间在1988年的差异(比如1988年3月29日),有一个更简单的方式来获得?此人的准确年龄
So, if I would want to get accurately, the difference between Today and a day in 1988(say 29th March 1988), is there an "easier" way to get the accurate age of this person?
我已经试过是:
DateTime March291988 = DateTime.Parse("29/03/1988");
TimeSpan ts = DateTime.Now.Subtract(March291988);
int years = (ts.Days/365);
更重要的是,问题是:如何从时间跨度转换为DateTime
More importantly, the question is: How to convert from TimeSpan to DateTime.
推荐答案
我有偏见,但我会使用野田佳彦时间:
I'm biased, but I'd use Noda Time:
var date1 = new LocalDate(1988, 3, 29);
var date2 = new LocalDate(2013, 1, 23); // See note below
var years = Period.Between(date1, date2, PeriodUnits.Years).Years;
基本上BCL不能提供的东西这样工作的一个非常简单的方法 - 你真的不的希望有一个时间跨度
,因为它没有固定到特定的开始/结束点。您可以从另一个减去一个年度
的值,然后调整,如果它做错误的事情,但它是一个有点恶心。
Basically the BCL doesn't provide a hugely easy way of working with things like this - you really don't want a TimeSpan
, because it's not anchored to a specific start/end point. You can subtract one Year
value from another and then adjust if it does the wrong thing, but it's a bit icky.
现在在你的原代码,您使用 DateTime.Now
。野田的时候,我们把时钟作为一个依赖, SystemClock.Instance
是正常的生产实施。一个 IClock
不知道时区 - 它只知道当前的时间瞬间 - 让你不得不说你是哪个时区兴趣,例如:
Now in your original code, you used DateTime.Now
. In Noda Time, we treat a clock as a dependency, with SystemClock.Instance
being the normal production implementation. An IClock
doesn't know about time zones - it just knows the current instant in time - so you have to say which time zone you're interested in. For example:
var today = clock.Now.InZone(zone).LocalDateTime.Date;
我知道这好像啰嗦,但它的隔离各种不同的转换,使这一切更明确。 (我可能会推出日期
在 ZoneDateTime
属性,以稍微降低这一点。)
I know this seems long-winded, but it's isolating all the different conversions to make it all more explicit. (I may introduce a Date
property on ZoneDateTime
to reduce this slightly.)
这篇关于如何准确地得到两个DateTime对象之间的差异"十年" [关闭,使用NodaTime]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!