user1687114
user1687114

Reputation:

Why can't I parse this string to date?

I am trying to parse a string to a DateTime:

string datum = "13/7/2013";
DateTime dtDatum = DateTime.ParseExact(datum, "yyyy-d-M", CultureInfo.GetCultureInfo("nl-NL"));

I'm getting "FormatException was unhandled by user code". I've tried several formats, and also different CultureInfo's, but nothing seems to work. I've searched on Google and this website, but can't seem to find an answer that gets rid of the exception.

Help is much appreciated.

Upvotes: 0

Views: 164

Answers (4)

hoang
hoang

Reputation: 1917

string datum = "13/7/2013";
DateTime dtDatum = DateTime.ParseExact(datum, "d/M/yyyy", CultureInfo.InvariantCulture);

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

Do not specify format, culture will do the job:

string datum = "13/7/2013";
DateTime dtDatum = DateTime.Parse(datum, CultureInfo.GetCultureInfo("nl-NL"));

This will parse "13/10/2013" also.

Upvotes: 2

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18411

ParseExact needs the day parsed to be in the exact format specified:

So either:

string datum = "13/7/2013";
DateTime dtDatum = DateTime.ParseExact(datum, "d/M/yyyy", CultureInfo.GetCultureInfo("nl-NL"));

or

string datum = "2013-13-7";
DateTime dtDatum = DateTime.ParseExact(datum, "yyyy-d-M", CultureInfo.GetCultureInfo("nl-NL"));

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45083

Your input format is not the same as the "format specifier that defines the required format of" the input.

The DateTime.ParseExact(String, String, IFormatProvider) method parses the string representation of a date, which must be in the format defined by the format parameter.

So your input would need to be string datum = "2013/13/7";; for this to match your format specifier.

Upvotes: 3

Related Questions