简体   繁体   中英

ASP.NET “String was not recognized as a valid DateTime.”

First off, I realize there's a million pages discussing this already. I have looked at least a hundred of them but cannot seem to make this work. My date and time is presented as a string, compiled from javascript to grab client's local time. It is formatted like this: 7/11/2015 8:34 PM. I currently have:

Dim datetimeformated = DateTime.ParseExact(lblDateTime.Text, "MM/dd/yyyy HH:mm tt", CultureInfo.InvariantCulture)

I have tried many different variants, but this should be correct I think, yet it does not work. Any help is greatly appreciated. TIA

The correct format for your case is: M/dd/yyyy h:mm tt , and perhaps even, M/d/yyyy h:mm tt , if you can have the day of the month as a single digit.


Explanation: Why your format string didn't work.

MM : means that you must always have 2 digits for the month, clearly not the case in your example.

dd : again, means that you must always have 2 digits for the day of the month. Is that the case? Adjust the parameter if needed.

HH : This actually means that you are expecting the hour value as 2-digits using the 24-hour clock (00-23), which is clearly wrong on both accounts. You can have a single digit, and you are not using the 24-hour clock, because you are using the AM/PM designator.

Relevant documentation link: Custom Date and Time Format Strings .

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