4b0
4b0

Reputation: 22323

Any difference between DateTime.Parse and Convert.ToDateTime?

Is there any difference between

Convert.ToDateTime

and

DateTime.Parse

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

Upvotes: 49

Views: 31361

Answers (4)

David
David

Reputation: 73564

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.

Upvotes: 40

Shubham Puri
Shubham Puri

Reputation: 41

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

Upvotes: 4

Bilal Sohail
Bilal Sohail

Reputation: 129

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.

Upvotes: 2

Pawan Mishra
Pawan Mishra

Reputation: 7268

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);
}

Upvotes: 1

Related Questions