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:
Error is:

String was not recognized as a valid DateTime.


Function of Custom Validator:

C#
protected void chkdate1(object sender, ServerValidateEventArgs e)
{
    IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-GB", true);
    DateTime from = DateTime.ParseExact(txt_from_date.Text, "MM/dd/yyyy HH:mm:ss", theCultureInfo);
    DateTime to = DateTime.ParseExact(txt_to_date.Text, "MM/dd/yyyy HH:mm:ss", theCultureInfo);
}


Custom Validation is:

C#
<asp:CustomValidator ID="scdt1" runat="server" OnServerValidate="chkdate1" ErrorMessage="To date not less than From date">
Posted
Updated 26-Jun-12 6:22am
v2
Comments
BoxyBrown 26-Jun-12 11:36am    
What values are in txt_from_date.Text and txt_to_date.Text?
BoxyBrown 26-Jun-12 11:48am    
I think better to use DateTime from = DateTime.Parse(txt_from_date.Text);
or get CultureInfo from client.
[no name] 27-Jun-12 0:09am    
in both textbox contain date only from ajax calendar.

1 solution

String was not recognized as a valid DateTime.
The way you are trying to convert text to date looks incorrect and you get the error.

Pick one:
1. Definding the culture info in which you want it to be converted.
C#
string dateString = @"06/26/2012";
DateTime date2 = Convert.ToDateTime(dateString,	System.Globalization.CultureInfo.GetCultureInfo("en-GB").DateTimeFormat);


Or

2.the ParseExact method:
C#
string dateString = @"06/26/2012";
DateTime date3 = DateTime.ParseExact(dateString, @"MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
 
Share this answer
 
Comments
[no name] 27-Jun-12 0:11am    
what is the meaning of '@' for writing ahead of string.
Sandeep Mewara 27-Jun-12 2:06am    
To not have issue with slashes! Read about '@' usage for strings.
[no name] 27-Jun-12 0:32am    
not working.......
Sandeep Mewara 27-Jun-12 2:06am    
Care to elaborate?

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