[英]Error Message as “String was not recognized as a valid DateTime.”
My Code: 我的代码:
DateTime? birthDate = DateTime.Parse(filterDictionary.ContainsKey("DOB") ? filterDictionary["DOB"] : string.Empty);
I am getting Error Message as "String was not recognized as a valid DateTime." 我收到错误消息,因为“字符串未被识别为有效的DateTime。” How to solve this issue.
如何解决这个问题。 Thanks.
谢谢。
The problem (at least one of them) is that you can't parse an empty string to a DateTime
. 问题(至少其中一个)是您无法将空字符串解析为
DateTime
。
Change your line of code to this to move the parsing only when you find the key, and return null instead of parsing when you don't have it: 将您的代码行更改为此,以仅在找到密钥时才移动解析,并在没有密钥时返回null而不是解析:
DateTime? birthDate = filterDictionary.ContainsKey("DOB") ? DateTime.Parse( filterDictionary["DOB"]) : (DateTime?) null;
The other problem might be that your dictionary DOB value is actually not possible to convert to a DateTime
. 另一个问题可能是您的字典DOB值实际上无法转换为
DateTime
。 If the above code does not work, please edit your question and post the value in filterDictionary["DOB"]
when you get this error. 如果以上代码不起作用,请在
filterDictionary["DOB"]
此错误时编辑您的问题,并将值发布到filterDictionary["DOB"]
。
Well DateTime.Parse
is always going to fail when you present it with an empty string. 当您使用空字符串显示
DateTime.Parse
时,它总是会失败。
It's not clear whether the time that you've seen this has been one where there has been data in the dictionary but it's invalid, or whether there's been no data and it's parsing string.Empty
. 目前尚不清楚,你已经看到了这个时间是否已经一个地方出现了字典中的数据,但它是无效的,或者是否存在一直没有数据,它的解析
string.Empty
。 Also note that DateTime.Parse
returns DateTime
, not DateTime?
还请注意,
DateTime.Parse
返回DateTime
,而不返回DateTime?
. 。 If you want the value to be
null
if the entry wasn't in the dictionary, I'd actually use: 如果您想在条目不在字典中的情况下将该值设置为
null
那么我实际上会使用:
DateTime? birthDate = null;
string dobText;
if (filterDictionary.TryGetValue("DOB", out dobText))
{
birthDate = DateTime.Parse(dobText);
}
Or perhaps: 也许:
string dobText;
DateTime? birthDay = filterDictionary.TryGetValue("DOB", out dobText)
? DateTime.Parse(dobText) : (DateTime?) null;
Note that you need to cast at least one of the second or third operands to null
here so the compiler can work out the type of the conditional expression. 请注意,您需要在此处将第二或第三操作数中的至少一个强制转换为
null
,以便编译器可以计算条件表达式的类型。
You should also consider whether a plain call to DateTime.Parse
is appropriate: 您还应该考虑对
DateTime.Parse
的普通调用是否合适:
DateTime.ParseExact
DateTime.ParseExact
TryParse
or TryParseExact
TryParse
或TryParseExact
CultureInfo.InvariantCulture
CultureInfo.InvariantCulture
的解析CultureInfo.InvariantCulture
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.