Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.TryParse should fail when found whitespace

Tags:

c#

.net

tryparse

DateTime.TryParse should fail when found whitespace.

Examples:

String Acceptable:       "2015-01-01"
String Not Acceptable 1: " 2015-01-01"
String Not Acceptable 2: "2015-01-01 "
String Not Acceptable 3: "2015 -01-01 "

I'm not passing DateTimeStyles parameter.

if (!DateTime.TryParse(StringDate, out Datetimedate)){...}

In case of StringDate has whitspaces the parsing doesn't fail. I want it to fail when there is any whitespace.

like image 818
Luís Ferreira Avatar asked Jul 16 '26 08:07

Luís Ferreira


1 Answers

The TryParse method is smart enough to trim the string.

If you want to enforce a specific format, use TryParseExact:

DateTime dateValue;

if (DateTime.TryParseExact(dateString, "yyyy-mm-dd", CultureInfo.InvariantCulture, 
                       DateTimeStyles.None, out dateValue))
   ...
like image 185
Patrick Hofman Avatar answered Jul 17 '26 21:07

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!