Monday, March 22, 2010

Three approaches to convert a string to a date in C#

string fileDate = "5/9/2010";
DateTime dt = Convert.ToDateTime(fileDate); //Can be used the same way as ParseExtract below.  It will throw a FormatException exception if it fails.

DateTime dt = DateTime.Parse(fileDate); //will try very hard to generate a DateTime object.  If the string has missing date elements, it will default to the current date and missing time elements default to 12:00:00 am.  After all efforts, if Parse cannot create a DateTime object, it will throw a System.FormatException exception.

DateTime.ParseExact(fileDate, "MMMM dd", null); //You pass a string, a format string the specifies the structure the time and date string must have, and an IFormatProvider reference that provides culture-specific information to the method.  If the IFormatProvider value is null, the current thread's culture information is used.  if it doesn't work, it will throw a System.FormatException exception.



No comments: