简体   繁体   中英

Converting the specified string representation of a date and time to its DateTime equivalent

Rephrasing the question found at SO .

Code 1 :

DateTime.TryParse("5-5-5-5" , CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal  , out result);

Code 2:

DateTime.TryParse("5-5-5-5.00" , CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal  , out result);

When the format is changed to 5-5-5-5.00 entire result changes ,Why does that happen ?Does that depend on Culture properties ?

The problem here is that in the first case it makes a guess as to what you mean and gives you a date. In the second case it cannot work out what you are meaning and so fails to parse. Luckily TryParse has a mechanism for reporting whether it succeeded or not, its return value. While the first returns true the second returns false and thus the value of result is meaningless and shouldn't be examined (though it seems is default(DateTime) ).

As I mentioned in comments when using unusual formats for your DateTime strings it is usually best to use DateTime.TryParseExact . This works very similarly except that you tell it exactly what format you expect the string to be in and it uses that to parse rather than trying its best guess of what you mean. You will still need to check the return value in case the input was in the wrong format (or you got your format specifier wrong).

Do like in this answer

But they tell system what the string is: "5-5-5-5" is a horrible string format for a date. The format string would proberbly be: "dMyh" in your case unless i misunderstand

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