Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 817
4b0 Avatar asked Nov 19 '11 07:11

4b0


People also ask

What does DateTime parse do?

The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.

What are the differences between Parse and ParseExact?

Parse() and ParseExact() are quite similar. However, in ParseExact() we can pass format as extra parameter which is not available in Parse(). Format parameter helps to convert a string date value to DateTime object when a date is different format like “11-23-2015”(Format should be “MM-dd-yyyy”).

How do I convert ToDateTime?

open System let convertToDateTime (value: string) = try let convertedDate = Convert. ToDateTime value printfn $"'{value}' converts to {convertedDate} {convertedDate.

How does DateTime TryParse work?

TryParse(String, IFormatProvider, DateTimeStyles, DateTime) Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.


2 Answers

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.

like image 116
David Avatar answered Oct 02 '22 16:10

David


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.

like image 33
Bilal Sohail Avatar answered Oct 02 '22 18:10

Bilal Sohail