[英]String was not recognized as a valid DateTime. 6-26-2015
I tried several Q&A in here and made this piece of code: The idea is to compare dt1 with dt2 and do something later. 我在这里尝试了几次问答,并编写了这段代码:这个想法是将dt1与dt2进行比较,然后再做一些事情。
date = row.Cells[3].Value.ToString();
DateTime dt1 = DateTime.ParseExact(date, "M/d/yyyy", CultureInfo.InvariantCulture);
dt1 = dt1.AddDays(-4);
String dateStr = DateTime.Now.ToString("M/d/yyyy");
DateTime dt2 = DateTime.ParseExact(dateStr, "M/d/yyyy", CultureInfo.InvariantCulture);
On the last line I am having this exception: 在最后一行,我遇到了这个异常:
String was not recognized as a valid DateTime.
无法将字符串识别为有效的DateTime。
While debugging this are the values: 在调试时,这些值为:
date = 06/05/2015
dt1 = "01-Jun-15 12:00:00 AM
datestr = 6-26-2015
Your format is incorrect if datestr
value is "6-26-2015" you should use this: 如果
datestr
值为“ 6-26-2015”,则格式不正确,应使用以下格式:
DateTime dt2 = DateTime.ParseExact(dateStr, "M-d-yyyy", CultureInfo.InvariantCulture);
ParseExact
tries to match the input string with the given format. ParseExact
尝试将输入字符串与给定格式匹配。
In your case input string is 6-26-2015
and format is M/d/yyyy
, -
and /
can not be matched so the exception is thrown. 在您的情况下,输入字符串为
6-26-2015
,格式为M/d/yyyy
, -
和/
无法匹配,因此将引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.