I am using DateTime.TryParse
method in my program to judge if a string value is DateTime
, then I notice this:
DateTime.TryParse("9.08", out DateTime dt)
// true
DateTime.TryParse("2.52", out DateTime dt)
// false
Why would this happened ?
DateTime.TryParse is parsed information in the current DateTimeFormatInfo
object, which is supplied implicitly by the current thread culture.
Because the DateTime.TryParse(String, DateTime) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results. If a specific date and time format will be parsed across different locales
In some cultures, DateTime
separator is .
rather than /
.
On my computer.
DateTime.TryParse
will Parse "9.08"
be this year '09/08'
, 2018/09/08
is a valid datetime
, so it's true
.
DateTime.TryParse
will Parse "2.52"
be this year '02/52'
, but there isn't 52nd days on February, 2018/02/52
isn't a valid DateTime
, so it will be false
.
I would use DateTime.TryParseExact to Parse DateTime because you can set your CultureInfo
and Parse
DateTime string be parameters and ensure that conforms to your expected format.
DateTime.TryParseExact("09.08",
"MM.dd",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out dt);
As per DateTime.TryParse
documentation:
returns a value that indicates whether the conversion succeeded.
As it couldn't parse "2.52"
to any valid date, it returned false
.
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