Madmenyo
Madmenyo

Reputation: 8584

Cannot convert dateTime string with Datetime.ParseExact

This is the exact string i have: 18-2-2014 00:00:00

My code bumps into this error:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: String was not recognized as a valid DateTime.

At this line:

newDateTime = DateTime.ParseExact(
                        part[0],
                        "dd-mm-jjjj hh:mm:ss", 
                        CultureInfo.InvariantCulture
                        ); //I tried a couple of time string variations, but it should be the above or "dd-m-jjjj hh:mm:ss".

What am i doing wrong?

Upvotes: 4

Views: 1139

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98810

mm specifier is for minutes. Use M specifier which is for months (1 to 12).

hh format is for 01 to 12 (12-hour clock). It doesn't have 00 as an hour. That's why you should use HH format which is for 00 to 23 (24-hour clock).

And there is no jjjj date and time format specifier which I think you want to use yyyy format.

var s = "18-2-2014 00:00:00";
var date = DateTime.ParseExact(s,
                              "dd-M-yyyy HH:mm:ss",
                               CultureInfo.InvariantCulture);
Console.WriteLine(date);

Output will be;

2/18/2014 12:00:00 AM

Here a demonstration.

For more information, take a look at;

NOTE: As Jeppe Stig Nielsen pointed, since we don't know your culture exactly (can be nl-BE or nl-NL) your ShortDatePattern day for is d not dd.

That's why you might need to use d format instead dd.

Upvotes: 3

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

Try This:

newDateTime = DateTime.ParseExact(part[0],"dd-M-yyyy HH:mm:ss", 
                    CultureInfo.InvariantCulture);

Upvotes: -1

Related Questions