简体   繁体   English

一个DateTime可以很好地解析,但另一个不是吗?

[英]One DateTime parses fine but the other doesn't?

I have an ASP site where I read two dates from two fields. 我有一个ASP网站,从两个字段读取两个日期。

The dates are generated using JavaScript and one of the two dates I need to read pass but the other doesn't. 这些日期是使用JavaScript生成的,我需要读取通行证的两个日期之一,而另一个则不需要。 Even though they are made the exact same way. 即使它们的制作方法完全相同。

So as you see here from my Immediate Window: 因此,正如您从“即时窗口”中看到的那样:

datepicker_start.Value
"03/10/2016"

datepicker_end.Value
"03/23/2016"

The first one parses fine, the second one does not: 第一个解析良好,第二个则没有:

DateTime start = DateTime.Parse(datepicker_start.Value);
DateTime end = DateTime.Parse(datepicker_end.Value);

It throws a FormatException on the end date: 它在结束日期引发FormatException:

DateTime.Parse(datepicker_end.Value)

threw an exception of type 抛出类型异常

System.FormatException: The String wasn't recognized as a valid DateTime. System.FormatException:字符串未被识别为有效的DateTime。

I cannot understand why this is happening. 我不明白为什么会这样。 If you need anything other than what I gave already please let me know as this is truly puzzling. 如果您除了我已经提供的东西以外还需要其他任何东西,请告诉我,因为这确实令人困惑。

DateTime.Parse uses standard date and time format of your current culture settings. DateTime.Parse使用当前区域性设置的标准日期和时间格式。

Probably your culture setting has dd/MM/yyyy as a standard format and since there is no 23rd month, your second line throws FormatException . 可能您的区域性设置将dd/MM/yyyy作为标准格式,并且由于没有第23个月,因此第二行将引发FormatException

I would suggest to use DateTime.ParseExact with a custom format like; 我建议将DateTime.ParseExact与类似的自定义格式一起使用;

DateTime end = DateTime.ParseExact(datepicker_end.Value,
                                   "MM/dd/yyyy",
                                   CultureInfo.InvariantCulture);

For example; 例如; if you debug your code, your start will be 3rd of October, not 10th of March. 如果您调试代码,则start时间为10月3日,而不是3月10日。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM