Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTimeFormatInfo.InvariantInfo vs CultureInfo.InvariantCulture

I am trying to parse DateTime, with an exact format being accepted from client input.

Which one is better

bool success = DateTime.TryParseExact(value, "dd-MMM-yyyy",
   DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dateTime);

OR

bool success = DateTime.TryParseExact(value, "dd-MMM-yyyy", 
    CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);

Of course, this code is inside a common static method that is called wherever parsing of date is required.

like image 897
Binoj Antony Avatar asked Oct 08 '09 07:10

Binoj Antony


Video Answer


2 Answers

If you look at the signature for DateTime.TryParseExact, it takes an IFormatProvider as the third argument. Both DateTimeFormatInfo.InvariantInfo and CultureInfo.InvariantCulture implement this interface, so you are actually calling the same method on DateTime in both cases.

Internally, if you use CultureInfo.InvariantCulture, its DateTimeFormat property is called to get a DateTimeFormatInfo instance. If you use DateTimeFormatInfo.InvariantInfo, this is used directly. The DateTimeFormatInfo call will be slightly quicker as it has to perform less instructions, but this will be so marginal as to make no difference in (almost) all cases.

The main difference between the two approaches is the syntax. Use whichever one you find clearest.

like image 182
adrianbanks Avatar answered Sep 24 '22 02:09

adrianbanks


They will give the same results.
And it is very unlikely there would be any difference in performance.

So use whatever you think is most readable. My choice would be DateTimeFormatInfo.InvariantInfo for being slightly more to the point.

like image 38
Henk Holterman Avatar answered Sep 23 '22 02:09

Henk Holterman