Is there any difference between
Convert.ToDateTime
and
DateTime.Parse
Which one is faster or which is more secure to use?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 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.
Method 3
DateTime.Parse will throw an Exception when a null string is passed, Convert.ToDateTime will return DateTime.MinValue on passing a null value.
Method 4
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);
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0