[英]DateTime.ParseExact gives String was not recognized as a valid DateTime.
I'm trying to parse a date string into a DateTime
variable. 我正在尝试将日期字符串解析为
DateTime
变量。 I've found out that ParseExact
is the way to do it, but I try this I get the error: 我发现
ParseExact
是这样做的方法,但我试试这个我得到错误:
String was not recognized as a valid DateTime. 字符串未被识别为有效的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
. 我已尝试使用
null
(恰好在另一页上工作)和CultureInfo.InvariantCulture
。
reader["startdate"].ToString()
output: 01-08-2012 15:39:09 reader["startdate"].ToString()
输出:01-08-2012 15:39:09
and 和
reader["nextdate"].ToString()
output: 01-08-2012 15:39:09 reader["nextdate"].ToString()
输出: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. 你在格式字符串中使用
hh
。 That's a 12-hour "hour of day" field. 这是一个12小时的“一天一小时”字段。 The value 15 isn't in range...
值15不在范围内......
You want HH
instead, which is the 24-hour specifier. 你想要
HH
,这是24小时的说明符。
See the MSDN custom date and time format strings documentation for more information. 有关详细信息,请参阅MSDN自定义日期和时间格式字符串文档 。
Most probably due to the difference between your Server locale and the UI locale 很可能是由于您的服务器区域设置和UI区域设置之间的差异
One easier method will be to specify the globalization details in the web.config 一种更简单的方法是在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. 我不确定这是否有帮助但是我使用了本文中的确切代码并且它对我有用,因为DateTime.ParseExact(dat,“dd / MM / yyy HH:MM”,CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles。没有)对我不起作用。
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 阅读本文我刚刚在网上发布: http : //rochcass.wordpress.com/2012/08/27/error-string-was-not-recognized-as-a-valid-datetime-solution/#more-350
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.