简体   繁体   English

无法将字符串识别为有效的DateTime。 2015年6月26日

[英]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.

相关问题 该字符串未被识别为有效的DateTime。 从索引26开始有一个未知词 - The string was not recognized as a valid DateTime. There is an unknown word starting at index 26 字符串日期未被识别为有效的日期时间。 - String date was not recognized as a valid DateTime.' 错误消息为“字符串未被识别为有效的DateTime。” - Error Message as “String was not recognized as a valid DateTime.” 无法将字符串识别为有效的DateTime。 引发异常 - String was not recognized as a valid DateTime. Throws an Exception 错误:字符串未被识别为有效的DateTime。 - Error: String was not recognized as a valid DateTime. 获取错误“字符串未被识别为有效的DateTime”。 - Getting error “String was not recognized as a valid DateTime.” 字符串未被识别为有效的日期时间。 将字符串转换为日期时间 - String was not recognized as a valid DateTime. Converting string to DateTime DateTime.ParseExact赋予String未被识别为有效的DateTime。 - DateTime.ParseExact gives String was not recognized as a valid DateTime. 迄今为止的字符串解析错误“字符串未被识别为有效的DateTime。” - String to date parsing error “String was not recognized as a valid DateTime.” “字符串未被识别为有效的DateTime。”Window 7计算机环境中出现错误 - “String was not recognized as a valid DateTime.” Error occur in Window 7 computer environment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM