Thursday, May 15, 2014

Convert string to DateTime object

Many times we need to convert a sting variable to datetime, and we use 'Convert.ToDateTime' method but it results throws a FormatException
See below snap
Convert.ToDateTime

in above case I have a date string and I was trying to convert it to date time but it fails and gives me exception "String was not recognized as valid Date Time" (this is one of the famous exception)

Tips to avoid error:
          When we use  'Convert.ToDateTime' method compiler assumes given date string in month,  day, and year respectively, If value contains only a date and no time, this method assumes a time of midnight (which may not right every time)
 To avoid this error you should know exact dateTime format of input string in order to convert it to dateTime object, Use DateTime.ParseExact Method resolve the issue
 see below snippet

string dt = "24/12/2010";
DateTime dt1;
//always use InvariantCulture for dateformat provider as it support large number of customized datetime formats
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
dt1 = DateTime.ParseExact(dt, "dd/MM/yyyy", provider);
MessageBox.Show("String successfully converted to DateTime" + dt1.Year); 

DateTime.ParseExact  method will, Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

The function can be used widely supported in following frames
- .NET Framework(1.1 to 4.5)
- .NET Framework Client Profile
- Portable Class Library
- .NET for Windows Store apps
- .NET for Windows Phone apps

This basic conversion snippet will help you get rid of error 'String was not recognized as valid Date Time'