简体   繁体   中英

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 ?

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 .

Except you are trying to understand every time string conversion of .NET Otherwise, you should not able to answer "why exactly would that happened?"

DateTime.TryParse is just a simple condition handling to prevent you getting an error when you do

Convert.ToDateTime(dateString)

Thus, DateTime.TryParse = false means you should not do Convert.ToDateTime to that string.

Oppositely, if a string to DateTime.TryParse = true , then it means that string should match the expectation of .NET date string (it means .NET know how to convert that string to DateTime).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM