49

Is there any difference between

Convert.ToDateTime

and

DateTime.Parse

Which one is faster or which is more secure to use?

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
4b0
  • 21,981
  • 30
  • 95
  • 142

4 Answers4

40

Per an answer on another forum from Jon Skeet...

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

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.

Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
David
  • 72,686
  • 18
  • 132
  • 173
  • 3
    "In short, Convert.ToDateTime() eliminates the code necessary to set the CultureInfo, which you'd have to do to use DateTime.Parse()" That's not true. You donn't have to set the CultureInfo to use DateTime.Parse(). DateTime.Parse has an overload that takes only 1 string and nothing else and it uses the current culture info without you having to pass it in. – Nick Feb 12 '13 at 16:32
4

DateTime.Parse will throw an Exception when a null string is passed, Convert.ToDateTime will return DateTime.MinValue on passing a null value.

Nappy
  • 3,016
  • 27
  • 39
2

DateTime.Parse has an overload that takes only one String and nothing else and it uses the current Locale info without you having to pass it in.

tomrozb
  • 25,773
  • 31
  • 101
  • 122
Bilal Sohail
  • 129
  • 9
1

The overloads of Convert.ToDateTime which take string as input parameter, internally invoked DateTime.Parse. Following is the implementation of Convert.ToDateTime.

public static DateTime ToDateTime(string value)
{
    if (value == null)
    {
        return new DateTime(0L);
    }
    return DateTime.Parse(value, CultureInfo.CurrentCulture);
}

In case of other overload, the parameter is casted into IConvertible interface and then the corresponding ToDateTime method is invoked.

public static DateTime ToDateTime(ushort value)
{
    return ((IConvertible) value).ToDateTime(null);
}
Pawan Mishra
  • 7,212
  • 5
  • 29
  • 39