I was writing a converter that takes a person's date of birth and produces their age in years. I wrote something that looked like this:
public class DateOfBirthToAgeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var date = value as DateTime?;
if (date == null) return null;
return (DateTime.Now - date).Years;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I found that there is no Years
property on the TimeSpan
that results from the subtraction of two DateTime
objects. I was somewhat surprised by this. I thought about why there might not be a Years
. I figured that it might be because of the leap day, but by that logic, there shouldn't be Days
because of daylight savings.
The absence of Months
made sense, since there is no standard month length.
I was able to write some different code to get the correct age, but I still really want to know why there is no Years
or Weeks
property on TimeSpan
. Does anyone know the reason?
TimeSpan
fits your purpose. Check this out: Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo – Dogear21st July
changes (property of a calendar). The duration ofa day
does not (A unit of time). – Lampmonth
is30 days
but the duration ofAugust
is31 days
? This is actually the way the programmers ignoring the leap seconds and daylight savings. – Kutch