2017-08-04 33 views
-1

我写了这个错误:获取有关解析听起来有效日期时间

Dim dtttm As DateTime = DateTime.Parse(value, 
    System.Globalization.CultureInfo.InvariantCulture) 

和得到传入的值是

17/07/30 12:00:00 AM 

但我得到的错误:

System.FormatException: 'String was not recognized as a valid DateTime.'

+0

您需要使用'ParseExact'并传递正确的格式,如果你要处理不寻常的格式,像当年来到这里第一::'DateTime.ParseExact(输入,“YY/MM/dd h:mm:ss tt“,CultureInfo.InvariantCulture)' –

+0

如果你的文化是美国的,它期望的是第一个月,所以它不会像17 – zzxyz

回答

6

InvariantCulture使用MM/dd/yy日期格式。您的输入格式为dd/MM/yy格式(1930年7月17日),或格式为yy/MM/dd格式(2017年7月30日)。我不知道。

您应该使用ParseExact相反,使用您的输入匹配的格式:

Dim dtttm As DateTime = DateTime.ParseExact(value, "dd/MM/yy h:mm:ss tt" 
    System.Globalization.CultureInfo.InvariantCulture) 

理想的情况下,避免模棱两可的数据。尽可能使用yyyy-MM-dd格式。
https://xkcd.com/1179/

+0

...为什么”不变“是美国的格式是我的东西我从来没有想过... –

+0

也许是因为微软是一家美国公司? – NetMage

+1

是的,除了我相信他的格式是yy/MM/dd ... –