简体   繁体   English

使用C#不将字符串识别为有效的DateTime

[英]String was not recognized as a valid DateTime using C#

i am comparing 2 date fields to see if the first date field is less than the 2nd one but i am getting this error "String was not recognized as a valid DateTime" and it is failing at this line 我正在比较2个日期字段,看看第一个日期字段是否小于第二个字段,但我收到此错误“字符串未被识别为有效的日期时间”,并且它在此行失败

DateTime Field2 = DateTime.Parse(gr.Cells[10].Text);

this is how this date field look like in my table: 2012-11-08 这就是我的表格中这个日期字段的样子:2012-11-08

DateTime Field1 = DateTime.Parse(gr.Cells[3].Text);
DateTime Field2 = DateTime.Parse(gr.Cells[10].Text);
DateTime strDate = System.DateTime.Now;
if (Field2 == null && Field1 < strDate)

使用ParseExact并指定格式“yyyy-MM-dd”或“yyyy-dd-MM”

Use DateTime.ParseExact : 使用DateTime.ParseExact

var res = 
    DateTime.ParseExact("2012-11-08", "yyyy-MM-dd", 
        CultureInfo.InvariantCulture);

According to the MSDN entry on DateTime.Parse : 根据DateTime.Parse上MSDN条目

The string s is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture. 使用当前线程文化隐式提供的当前DateTimeFormatInfo对象中的格式信息来解析字符串s。

You are most probably getting the error because your current thread culture has a vastly different date format than that of the string you have provided. 您最有可能收到错误,因为您当前的线程文化的日期格式与您提供的字符串的日期格式大不相同。

What you can do is to specify the format that you will be using for the date: 您可以做的是指定您将用于日期的格式:

 DateTime.ParseExact(gr.Cells[10].Text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);

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

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