简体   繁体   中英

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?

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 .

Try This:

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

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