Monday, November 20, 2006

Elegant way to parse a string into DateTime instance in C#

I am reviewing some code and came across the following code:

try
{
if (str.Trim() == "") return DateTime.Now;
return (new DateTime(int.Parse(str.Substring(0, 4)), int.Parse(str.Substring(4, 2)), int.Parse(str.Substring(6, 2))));
}
catch
{
return DateTime.Now;
}


Obviously, an exception would be thrown if the string is not in the right format.

So, I looked for a clean way to parse the string into a DateTime instance and came across the following line at (http://www.csharphelp.com/board2/read.html?f=1&i=38662&t=38662)

DateTime.Parse(long.Parse(str).ToString("####/##/##"))

I am not sure if it is more efficient or not compared to the original code snippet I had above, but certainly very elegant, is n't it? We do not have to worry about slicing and joining the string, and instead let the underlying framework class handle all the error checking and if it can't convert it to a valid DateTime instance and then let it throw an exception.

Is not this clean and elegant?

Your comments are welcome.