In this article I will explain with an example, how to resolve the following error: String was not recognized as a valid DateTime in C# and VB.Net.
 
 

Error

The following error occurs when you try to get Date value from string which is not in proper Date format.
Server Error in '/' Application.

String was not recognized as a valid DateTime.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: String was not recognized as a valid DateTime.
 
Exception - String was not recognized as a valid DateTime in C# and VB.Net
 
 

Solution

The solution to this problem is to make sure the DateTime in string is in correct format.
 
 

Cause

Exception is raised due to when the format of the DateTime string does not match with the format specified.
//Incorrect Format - Throws Error.
DateTime dateTime2 = DateTime.ParseExact("12-13-2024", "yyyy.dd.MM", CultureInfo.InvariantCulture);
 
Exception - String was not recognized as a valid DateTime in C# and VB.Net
 
Once the correct DateTime format is specified, the string to DateTime conversion will work.
//Correct Format and No Error.
DateTime dateTime = DateTime.ParseExact("12-13-2024", "MM-dd-yyyy", CultureInfo.InvariantCulture);