Parse(), TryParse() and ParseExact() Methods
The DateTime struct has a lot of methods for parsing a string into a DateTime. Most everyone has used the Parse() method, but the cost of the exception throws on an error can become a performance bottleneck if improperly formatted input is possible.
string logString = "20111231 031505";
DateTime logEntryTime;
try
{
logEntryTime = DateTime.Parse(logString);
}
catch (Exception ex)
{
// the above will throw
Console.WriteLine("Didn't understand that DateTime.");
}
The TryParse() methods have much the same signature as Parse(), except that they take a final out parameter of DateTime where the value is placed (if successful), and return a bool that indicates if the parse was successful or not. Use TryParse() when you want to be able to attempt a parse and handle invalid data immediately (instead of bubbling up the exception). Thus, the code above could be rewritten as:
string input = "02/30/2010 12:35";
DateTime recordDate;
// let's say we want to parse the date, but if we can't, then we'll assume now...
if(!DateTime.TryParse(input, out recordDate))
{
recordDate = DateTime.Now;
}
What if you were reading data from a file, and the DateTime contained in it was a non-standard format. For example, let’s say we’re parsing a log file that begins with a timestamp that is a date in the format yyyyMMdd HHmmss (like 20111231 031505 for 12/31/2011 03:15:05 AM), in this situation you should use ParseExact() when the format you are expecting is not a standard format, or when you want to limit to one particular standard format for efficiency.
string logString = "20111231 031505";
DateTime logEntryTime;
logEntryTime = DateTime.ParseExact(logString, "yyyyMMdd HHmmss", null);