Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DateTime.TryParse makes me confused

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 ?

like image 930
1pgjy Avatar asked Jul 23 '18 06:07

1pgjy


Video Answer


2 Answers

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);
like image 143
D-Shih Avatar answered Oct 17 '22 11:10

D-Shih


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.

like image 34
Adelin Avatar answered Oct 17 '22 10:10

Adelin