[英]String was not recognized as a valid DateTime
"String was not recognized as a valid DateTime
" error was occurred when I tried to convert a string to DateTime
. 当我尝试将字符串转换为DateTime
时,发生“未将字符串识别为有效的DateTime
”错误。
I stored the current date using getDate()
method into my DB. 我使用getDate()
方法将当前日期存储到数据库中。 And it was set as DateTime
. 并将其设置为DateTime
。 I retrieved it and display in a DetailsView
. 我检索了它并显示在DetailsView
。 And later I retrieve from the DetailsView
and set on a label. 然后,我从DetailsView
检索并设置在标签上。
Label ForgotDatelbl = new Label();
ForgotDatelbl = (Label)DetailsView2.FindControl("ForgotPwLabel");
DateTime ForgotDate = DateTime.ParseExact(ForgotDatelbl.ToString(),
"d/M/yyyy hh:mm:ss tt", null); //here is the error
if (DateTime.Now < ForgotDate.AddMinutes(3)) {
}
Source Error: 源错误:
Line 28: DateTime ForgotDate = DateTime.ParseExact(ForgotDatelbl.ToString(),"d/M/yyyy hh:mm:ss tt", null);
Line 29:
Line 30: if (DateTime.Now < ForgotDate.AddMinutes(3))
and in my database the time was like this - 20/7/2012 7:42:19 PM
在我的数据库中,时间是这样的20/7/2012 7:42:19 PM
EDIT 编辑
IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-GB", true);
DateTime ForgotDate = DateTime.ParseExact(ForgotDatelbl.ToString(), "dd/M/yyyy hh:mm:ss tt", theCultureInfo);
However, error still remain.. 但是,错误仍然存在。
Try to change the format with only 1h specifier: 尝试仅使用1h说明符来更改格式:
//20/7/2012 7:42:19 PM
"dd/M/yyyy h:mm:ss tt",
在重载方法中使用Culture
Please consider the following 请考虑以下
string dateString = "20/7/2012 7:42:19 PM";
//can be this in your case: string dateLabel = ForgotDatelbl.Text;
var culture = new CultureInfo("en-GB");
var date = DateTime.Parse(dateString, culture, DateTimeStyles.RoundtripKind);
This parses an exact match of what you want. 这将解析出您想要的精确匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.