Eddie Vu
Eddie Vu

Reputation: 65

how to check date in c#? (interactive program)

i'm learning to create an interactive program where users type their exact birthday(month; day, year) at separate lines but i don't know how to use DateTime.Now property. I know month has to be from 1 to 12 so i wrote

if (month<1  && month>13)
{Console.WriteLine("error");}

+with "year" field, it has to be from 18 to 100 years ago. i used

if(year >2000 &&year <1918)
{Console.WriteLine("error");}

the problem is,i have to change the conditions each year . and i also want to check the relationship between "day" field and month field. for example February only has 28 days; if day field exceeded, prompt "error". I know it's complicate but i don't know a lot about DateTime property and how to cooperate that to a condition statement . please help. thanks

Upvotes: 1

Views: 97

Answers (2)

Mahesh
Mahesh

Reputation: 873

 dateString = "2011-29-01";//concatenate fields to get date
 string format = "yyyy-dd-MM";
 try
 {
   //for ParseExact : https://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx
   result = DateTime.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
  }
  catch (FormatException)
  {
    Console.WriteLine("{0} is not in the correct format.", dateString);
   }

   if(result.AddYears(18)<=Datetime.now){
   //write your logic
   }

Upvotes: 1

TheGeneral
TheGeneral

Reputation: 81583

You can use

DateTime.Year Property

Gets the year component of the date represented by this instance.

DateTime.DaysInMonth Method (Int32, Int32)

Returns the number of days in the specified month and year.

Eg

var currentYear = DateTime.Now.Year;

if (year > currentYear - 18 || year < currentYear - 118)
{
   Console.WriteLine("error"); 

}

and

var days = DateTime.DaysInMonth(year, 2);

// calculate the days in February for a given year
if (day > days || day < 0)
{
   Console.WriteLine("error");

}

Upvotes: 0

Related Questions