String was not recognized as a valid DateTime
The error shown in question might have been thrown by
In the above code the
By default the
So, when
To avoid this error the appropriate culture can be used as follows
When
Convert.ToDateTime method as shown below:string dateString = "20/08/2013";
//The following code throws
//FormatException: String was not recognized as a valid DateTime
DateTime date = Convert.ToDateTime(dateString);
dateString represents Date in the Day/Month/Year format.By default the
en-US culture is used by .NET according to which the Date is in Month/Day/Year format. So, when
ToDateTime method is used it throws error as 20 is out of Month range.To avoid this error the appropriate culture can be used as follows
string dateString = @"20/05/2012";
DateTime date2 = Convert.ToDateTime(dateString,
System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
DateTime date3 = DateTime.ParseExact(dateString, @"d/M/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
When
TryParse method is used as shown below
bool result = DateTime.TryParse(dateString,out date4);
the parsing fails, but it will not throw error, rather it returns false indicating that the parsing failed.
Comments
Post a Comment