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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With