Elliot Morgan
Elliot Morgan

Reputation: 133

How to calculate how many days until someone will turn 18 using their date of birth in VB?

For a computer science assignment I need to calculate how many days it will be until the user turns 18, using their date of birth.

Dim dateToday As Date = Date.Today()

Dim ageNow As Integer = dateToday.Subtract(birthDate).Days

' 6750 is 365 * 18
Dim daysEighteen As Integer = 6750 - ageNow

MsgBox("You will be 18 in " & daysEighteen)

This is the code I have at the moment, however when tested it doesn't come up with the correct output.

This isn't the entire code but I have just included the necessary lines for this part of the program.

Thanks in advance.

Upvotes: 0

Views: 120

Answers (2)

Elliot Morgan
Elliot Morgan

Reputation: 133

This is the finished program, with commenting.

Public Class Form

Private Sub btnEnter_Click(sender As System.Object, e As System.EventArgs) Handles btnEnter.Click

    ' Stores the textboxes as variables
    Dim name As String = txtName.Text
    Dim birthDate As Date = dtpBirthDate.Text
    Dim electionDate As Date = dtpElectionDate.Text

    ' This is the age the user will be on the date of the election
    Dim ageElection As Integer = electionDate.Subtract(birthDate).Days

    ' If the user is 18 or older, it outputs that they are. If they're not, it calculates how many days
    ' it will be until they are and displays it.
    If (ageElection / 365) > 18 Then

        ' Outputs that the user is 18 or older
        MsgBox("You are 18 or older!")

    Else

        ' This is when the user will turn 18
        Dim adultDate As Date = birthDate.AddYears(18)

        ' This calculates how many days it will be until the user is 18, using when they turn 18
        Dim daysLeft = adultDate.Subtract(DateTime.Today).Days

        ' Outputs that the user is younger than 18 and outputs how many days until they're 18
        MsgBox("You are younger than 18! You will be 18 in " & daysLeft)

    End If

End Sub

End Class

Upvotes: 0

Steve
Steve

Reputation: 216293

I would use a different method. Add 18 years to the birthdate and then subtract the today date. This should avoid the error implicit in your calculation (365*18 doesn't count the leap years)

Dim birthDate = New DateTime(1999,1,1)
Dim adultDate = birthDate.AddYears(18)
Console.WriteLine(adultDate.ToString("MM/dd/yyyy"))    
Dim daysLeft = adultDate.Subtract(DateTime.Today).Days
Console.WriteLine(daysLeft)

Upvotes: 1

Related Questions