Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
I'm currently trying to make a simple program that will ask a user in a console window to give me his year of birth. I will then subtract it from the current year and compare it to 18. I made an int for date.time.year - userdateofbirth and am trying to compare that to 18 to give an if then statement . If over 18 they will be able to continue, if not then they get rejected. My code so far is

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string Thanks;
            Console.WriteLine("Thank you for choosing to shop with us");
            Console.ReadLine();

            string Birth;
            int Birthint;
            Console.WriteLine("To complete your purchase, please enter your date of birth.");
            Birth = Console.ReadLine();
            Birthint = Convert.ToInt32(Birth);
            Console.ReadLine();

            Console.WriteLine("This year is " + DateTime.Now.Year);
            Console.WriteLine("You are " + (DateTime.Now.Year - Birthint) + " years old.");
            Console.ReadLine();

            int Oldint = (DateTime.Now.Year - Birthint);
            Oldint = Convert.ToInt32(Oldint);






            if (Oldint >= 18)


                //you are over 18

            if (Oldint <= 18)

                //you are under 18



                Console.ReadLine();













        }
    }
}



any suggestions on where to go from here?
Posted
Comments
Tomas Takac 7-May-15 17:21pm    
What's your question?
Wombaticus 7-May-15 17:49pm    
Next step si to take account of the current month and day, to see whether or not they have turned 18 if the current year - their date of birth = 18
ChrisCreateBoss 7-May-15 18:04pm    
If the given age is under 18, you can show a Message Box saying that you must be older than 18 years to make the purchase. But if the age is above 18 you can show a message box or just use the console to say "Your purchase has been completed! Thank you!"
Florian Braun 8-May-15 1:50am    
But I would strongly suggest to change the second if to just else {// do something}

1 solution

To calculate age, use something similar to:
C#
DateTime date1 = new DateTime(2001,1,15);
DateTime date2 = DateTime.Today;

int age = date2.Year - date1.Year;

Console.WriteLine("You are {0} 18 years old", age<18 ? "under" : "over");



More about time difference calculating: TimeSpan Structure[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900