How can I display an age as Years, Months, Days from a datetime picker value. Eg:
Datetimepicker value = #1/11/2014#
Today = #1/12/2015#.
The final result would be "1 Year, 0 Months, 1Day(S)". But getting that result is more than just subtracting the DateTime.Year
values and so forth. Does anybody know a mathematics formula or mathematics calculation about that?
This method is very straight forward and simple.
Creating loops and class properties is not needed.
This will work with both real
Date
types andStrings
that are dates:Example result: 1 Year 0 Months 1 Day(s)
you must add this to get a complete result: sDays = (DateDiff(DateInterval.Day, dBirthDay, dToday)) - sMonths * 30
Here is a
DateTimeSpan
Type which returns an object like aTimeSpan
representing the Yrs, Months, Days elapsed between 2 dates. It loops thru the time units to increment them until the smaller date matches the larger. The resulting increments are then returned in a newDateTimeSpan
object.Usage:
This will give the same result:
Result:
3 Yrs, 8 Months and 10 Days
Notes:
- It works only on proper
DateTime
types, not strings which look like dates. Use literals (#...#
) orDateTime
variables. When using aDateTimePicker
, use.Value
not.Text
.- It does not do negative values, so the order of values passed does not matter
- When calculating, it increments a
DateTime
variable so, it should properly account for leap daysThis is based on some C# code I found long ago in a blog (or perhaps even from an SO answer or question). Cant find it just now to cite the original.
This method uses loops to work this backwards, but I believe this is the only accurate way to do this and get the values always correct. This is because it is more complicated than you might think - you need to adjust for leap years, etc.
Usage:
Prints: