calculate age from date of birth

C

Chris Bower

In VB you can just use the DateDiff function, in C# use the TimeSpan
structure.
 
T

TJS

I added

"Imports System.DateTime" to my vb file, but keep getting error on
"datediff" when I try to compile ?
 
T

TJS

I added

"Imports System.DateTime" to my vb file, but keep getting error on
"datediff" when I try to compile ?
 
Joined
Sep 7, 2010
Messages
1
Reaction score
0
Some extension methods that may help

Here are some extension methods I frequently use when needing to calculate age. The first two extend TimeSpan to add a Years and TotalYears value to TimeSpan, the second extends a DateTime to give an Age (int) when passed a date to calculate the age from.

Code:
Namespace MyFunctions
    static class MyExtensions

        private const double YEAR_CALC = 365.2425;

        public static int Years(this TimeSpan ts) {
            return (int)Math.Floor(ts.TotalYears());
        }
        public static double TotalYears(this TimeSpan ts) {
            return ((double)ts.Days) / YEAR_CALC;
        }
        public static int Age(this DateTime dob, DateTime fromDate) {
            TimeSpan ts = fromDate.Subtract(dob);
            int age = ts.Years();
            [COLOR="green"]//will never return negative years - if this is desired, [/COLOR]
            [COLOR="green"]// just return age[/COLOR]
            return Math.Abs(age);
        }
    }
}

To use these, just add the following to the top of your class and the methods will be available on each of those types.

Code:
using MyFunctions.MyExtensions;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top