HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Attempt to calculate age in VB.NET

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
netagecalculateattempt

Problem

I am working on an app where I have to calculate the age of a person. Inside of my age class I have a function that is designed to account for leap year. Is there anything I am missing or could improve upon? I would have though this would have been more complicated so I am not confident in my method or my test case.

The function:

Function calculateAge() As Integer

    Dim age As Integer

    Try
        If Not Birthdate.Day.Equals(29) And Birthdate.Month.Equals(2) Then
            age = todaysDate.Year - Birthdate.Year
        Else
            age = todaysDate.Year - Birthdate.Year - 1
        End If

        Return age
    Catch ex As Exception
        Console.WriteLine(ex.ToString)
        Return Nothing
    Finally
        age = Nothing
    End Try

End Function


The test:

Sub Main()

    'Test calculate age function'
    Console.WriteLine(chip.calculateAge)

    'Test calculate age function with a February 29th birthday'
    Dim steve As New clsAge("Steve")
    With steve
        .Birthdate = #2/29/2008#
    End With

    Dim date1 As DateTime = #2/29/2000#
    Dim date2 As DateTime = #2/28/2009#
    Dim age As Integer

    Console.WriteLine(date1.Day.ToString)

    If Not date1.Day.Equals(29) And date1.Month.Equals(2) Then
        age = date2.Year - date1.Year
        Console.WriteLine(age.ToString)
    Else
        age = date2.Year - date1.Year
        age = age - 1
        Console.WriteLine(age.ToString())
    End If

    Console.ReadLine()

End Sub

Solution

If you'd like to avoid magic strings when hardcoding 365.25 in your code, you can use the following code:

VB

Dim date1 As Date = DateTime.Parse("5/14/1994")
Dim date2 As Date = DateTime.Parse("5/13/2013")

Dim yearsOld as Integer = date2.Year - date1.Year
If date1.AddYears(yearsOld) > date2 Then yearsOld -=1

Console.WriteLine(yearsOld) '18


C#

var date1 = DateTime.Parse("5/14/1994");
var date2 = DateTime.Parse("5/13/2013");

int years_old = date2.Year - date1.Year;
if (date1 > date2.AddYears(-years_old)) years_old--;

Console.WriteLine(years_old); //18


I'm also suspicious (though I have not run enough test cases to confirm) that there are some pair of dates with the right number of leap years that will break the functionality implemented based on days of the year.

I wrote a blogpost about calculating age from dob as well, although it's in VB.NET

Context

StackExchange Code Review Q#10263, answer score: 2

Revisions (0)

No revisions yet.