Posts

Showing posts from July, 2013

String was not recognized as a valid DateTime

The error shown in question might have been thrown by 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);     In the above code the 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 us...