简体   繁体   中英

DateTime.ParseExact gives String was not recognized as a valid DateTime.

I'm trying to parse a date string into a DateTime variable. I've found out that ParseExact is the way to do it, but I try this I get the error:

String was not recognized as a valid DateTime.

string timeFormat = "dd-MM-yyyy hh:mm:ss";
DateTime startDate = DateTime.ParseExact(reader["startdate"].ToString(), timeFormat, CultureInfo.InvariantCulture);
DateTime nextDate = DateTime.ParseExact(reader["nextdate"].ToString(), timeFormat, null);

I've tried both with null (which happens to work on another page), and the CultureInfo.InvariantCulture .

reader["startdate"].ToString() output: 01-08-2012 15:39:09

and

reader["nextdate"].ToString() output: 01-08-2012 15:39:09

I think it should work, but it doesn't.

Somebody have an idea what is wrong? :)

You're using hh in your format string. That's a 12-hour "hour of day" field. The value 15 isn't in range...

You want HH instead, which is the 24-hour specifier.

See the MSDN custom date and time format strings documentation for more information.

Most probably due to the difference between your Server locale and the UI locale

One easier method will be to specify the globalization details in the web.config

like

<configuration>
   <system.web>
      <globalization culture="en-GB"/>
   </system.web>
</configuration>

OR in more detail

<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="en-GB" uiCulture="en-GB" />

But be sure this wont clash with your application in general

试试这个有效

DateTime.ParseExact("01-08-2012 15:36:25", "dd-MM-yyyy HH:mm:ss", null);

I am not sure if this helps but I used the exact code from this article and it worked for me because the DateTime.ParseExact(dat, "dd/MM/yyy HH:MM", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None) did not work for me.

Read this I just posted it online: http://rochcass.wordpress.com/2012/08/27/error-string-was-not-recognized-as-a-valid-datetime-solution/#more-350

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