Click here to Skip to main content
15,911,315 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi friends,
I want to validate console input for date. For example, if i write year = 1000, it give me a message.
I wrote code like this:
in Main
Birthdate b1 = new Birthdate();
b1.birth=b1.CheckDate( Convert.ToDateTime(Console.ReadLine()));

in Birthdate class

SQL
public DateTime CheckDate(DateTime d)
        {
            if (d.Year < 1990 && d.Month < 1 & d.Day < 1 )
            {
                Console.WriteLine("error");
                d  =DateTime.Parse("0-0-0000" );
                return d;
            }
            else
            {
                return d;
            }
        }
Posted
Comments
TrushnaK 21-Oct-13 2:01am    
if (d.Year < 1990 && d.Month < 1 & d.Day < 1 )
this is not enough condition for validate date.
you have to check year , month > 12 and day according to month.
also consideration for leap year.
Elham.Deljooei 21-Oct-13 2:14am    
I've changed it like this:
public DateTime CheckDate(DateTime d)
{

if ((d.Year < 1990 && d.Year > DateTime.Today.Year) && (d.Month < 1 && d.Month > 12) && (d.Day < 1 && d.Day > 31))
{
Console.WriteLine("error");
d =DateTime.Parse("0-0-0000" );
return d;
}
else
{
return d;
}
}
But when i enter 1-1-1000 in console, it calculate birthdate and return answer.

Thanks,
Elham
Richard MacCutchan 21-Oct-13 4:25am    
You are using the && operator instead of ||. The year cannot be less than 1990 AND greater than this year.
Elham.Deljooei 21-Oct-13 5:19am    
Excuse me,
I've changed it like this:
if ((d.Year < 1990 || d.Year > DateTime.Today.Year) && (d.Month < 1 || d.Month > 12) && (d.Day < 1 || d.Day > 31))
But it don't work truly. :(

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