Why use DateTime.TryParse() instead of Convert.DateTime()

Convert.ToDateTime() uses DateTime.Parse() internally, with the current culture - unless you pass it null, in which case it returns DateTime.MinValue.

In short, Convert.ToDateTime() eliminates the code necessary to set the CultureInfo, which you'd have to do to use DateTime.Parse().

Note: If you're not sure string is a valid DateTime, use neither and instead, use DateTime.TryParse().

If you're sure the string is a valid DateTime, and you know the format, you could also consider the DateTime.ParseExact() or DateTime.TryParseExact() methods.

Please note that there may be certain cases when the DateTime.Parse() method fails (since Convert.ToDateTime() uses DateTime.Parse() internally, Convert.ToDateTime() will also fail).

Consider the scenario given below:

If user passes an invalid date format then the method DateTime.Parse() will throw a FormatException.

// throws FormatException, not a valid format
var dt1 = DateTime.Parse("");

// throws FormatException, February doesn’t have a 30th day, not a valid date
var dt2 = DateTime.Parse("02/30/2010 12:35");

Note: It is recommended to use DateTime.TryParse() method to avoid unexpected exceptions especially when accepting inputs from users.

It should be noted that DateTime.Parse() actually calls DateTime.TryParse() and just throws the exception in the event TryParse() returns false. That is, Parse() is roughly equivalent to:

// rough psuedo-code of Parse()
public DateTime Parse(string inputString)
     DateTime result;
     if (!DateTime.TryParse(inputString, out result))
         throw new FormatException(...);
     return result;

So calling DateTime.TryParse() directly is more efficient because it avoids the wrapper call, and it doesn’t allocate and throw an unneeded exception in the case of an error.

No comments:

Post a Comment