String To DateTime Conversion In C#

String To DateTime Conversion In C#

Convert.ToDateTime()

Provider: It is an object which provides culture specific info.

Value: It is string representation of time and date.

ToDateTime(string value, IFormatProvider provider)

CultureInfo culture = new CultureInfo("en-US");    
DateTime tmpDate = Convert.ToDateTime("1/1/2020 12:11:14 PM", culture);
// Convert.ToDateTime()  
string dateString = null;  
  
// Convert a null string.  
DateTime dateTime10 = Convert.ToDateTime(dateString); // 2/2/0002 12:00:00 AM  
dateString = "not a date";  
// Exception: The string was not recognized as a valid DateTime. 
// There is an unknown word starting at index 0.  
DateTime dateTime = Convert.ToDateTime(dateString);  
             
dateString = "Mon Dec 29, 2015";  
// Exception: String was not recognized as a valid DateTime because the day of week was incorrect.  
DateTime dateTime1 = Convert.ToDateTime(dateString);

DateTime.Parse()

string dateString = null;  
// Exception: Argument null exception
DateTime dateTime = DateTime.Parse(dateString);

 

2020-02-28