How to accurately get difference(in years) between two DateTime objects in “Years”?
DateTime.Subtract() gives difference in TimeSpan and the maximum denomination is Days.
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?
What I’ve tried is:
DateTime March291988 = DateTime.Parse("29/03/1988");
TimeSpan ts = DateTime.Now.Subtract(March291988);
int years = (ts.Days/365);
More importantly, the question is: How to convert from TimeSpan to DateTime.
I’m biased, but I’d use Noda Time:
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 oneYearvalue from another and then adjust if it does the wrong thing, but it’s a bit icky.Now in your original code, you used
DateTime.Now. In Noda Time, we treat a clock as a dependency, withSystemClock.Instancebeing the normal production implementation. AnIClockdoesn’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:I know this seems long-winded, but it’s isolating all the different conversions to make it all more explicit. (I may introduce a
Dateproperty onZoneDateTimeto reduce this slightly.)