"String was not recognized as a valid DateTime
" error was occurred when I tried to convert a string to DateTime
.
I stored the current date using getDate()
method into my DB. And it was set as DateTime
. I retrieved it and display in a DetailsView
. And later I retrieve from the DetailsView
and set on a label.
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
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:
//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.
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.