Luís Ferreira
Luís Ferreira

Reputation: 33

DateTime.TryParse should fail when found whitespace

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.

Upvotes: 2

Views: 741

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157058

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))
   ...

Upvotes: 11

Related Questions