Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.TryParseExact does not return correct response

Tags:

c#

datetime

Why would

 DateTime.TryParseExact("08/10/2013", "dd/MM/yyyy", null, DateTimeStyles.None, out dateValue)  

return false?

like image 229
yuben Avatar asked Apr 16 '26 08:04

yuben


2 Answers

Use CultureInfo.InvariantCulture instead of null.

It tells the compiler that the format is culture-independent.

DateTime.TryParseExact("08/10/2013", 
                       "dd/MM/yyyy", 
                       CultureInfo.InvariantCulture, 
                       DateTimeStyles.None, 
                       out dateValue);`

If you use null, it is inferred as CultureInfo.CurrentCulture(msdn: "If provider is null, the CultureInfo object that corresponds to the current culture is used"). Also, since it's not that clear, the problem is that / is replaced by the provided culture's date-separator. It has a special meaning. http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#dateSeparator

Here is a running example

enter image description here

like image 156
Nikhil Agrawal Avatar answered Apr 18 '26 22:04

Nikhil Agrawal


Because you passed null for the IFormatProvider parameter. Try passing CultureInfo.InvariantCulture instead

EDIT As others mentioned, the actual reason is that / in the string to parse is itself translated using the rules provided by IFormatProvider. When you pass null the default value of CultureInfo.CurrentCulture is used.

like image 40
Panagiotis Kanavos Avatar answered Apr 18 '26 20:04

Panagiotis Kanavos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!