Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
string dateToformat = "dd/MM/yyyy";
DateTime dateTo = DateTime.ParseExact(tb_DateTo.Text, dateToformat, CultureInfo.InvariantCulture);

if (dateFrom == default(DateTime))
            {
                returnMessage += "Date From cannot be blank! <br />";
            }

There is an error, if I left blank my date from, it will have string was not a recognized datetime. I am not sure. Please help. Thanks.
Posted
Updated 31-Jan-14 4:39am
v2

Using string.IsNullOrEmpty will help check if there is any text. you can even use .Trim()

C#
DateTime dateFrom;

if (string.IsNullOrEmpty(tb_DateFrom.Text.Trim()))
{
    msg1 += "Date From cannot be blank! <br />";
}
else
{
    string dateFromformat = "dd/MM/yyyy";
    dateFrom = DateTime.ParseExact(tb_DateFrom.Text, dateFromformat, CultureInfo.InvariantCulture);
}


you can also use DateTime.TryParse(dateString, out convertDateTime);
 
Share this answer
 
v3
Comments
Member 10548723 31-Jan-14 10:46am    
I declared my variable as a DateTime, this method is for string
bowlturner 31-Jan-14 10:49am    
Well your code is off a little. 'dateFrom' is not declared anywhere in the code you posted. Give us the actual code and error and we can give better solutions.
Member 10548723 31-Jan-14 10:53am    
Actually my dateFrom is inside this method to check if is empty

private string carinput(DateTime datefrom, DateTime dateTo)

{

if (dateFrom == default(DateTime))
{
returnMessage += "Date From cannot be blank! <br />";
}
if (dateTo == default(DateTime))
{
returnMessage += "Date To cannot be blank! <br />";
}

}

Is wrong?
bowlturner 31-Jan-14 10:59am    
If someone is typing in a date, it starts as a string somewhere. You need to check if the string is null or empty before you try to convert it to a date. Then using DateTime.TryParse can try to parse the input string without throwing and error.
Member 10548723 31-Jan-14 11:05am    
I try something like this

string dateFromformat = "dd/MM/yyyy";
DateTime dateFrom = DateTime.ParseExact(tb_DateFrom.Text, dateFromformat, CultureInfo.InvariantCulture);

if (String.IsNullOrEmpty(tb_DateFrom.Text))
{
msg1 += "Date From cannot be blank! <br />";
}
When validating or working with datetimes always should be validate before converting.

C#
if (string.IsNullOrEmpty(tb_DateTo.Text.Trim()))
{
    returnMessage += "To Date cannot be blank!";
}

if (string.IsNullOrEmpty(dateFrom.Trim()))
{
    returnMessage += "Date From cannot be blank!"; 
}

//next steps
 
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