简体   繁体   English

c#DateTime转换错误-无法将字符串识别为有效的DateTime

[英]c# DateTime convert error - String was not recognized as a valid DateTime

I keep getting an error when trying to convert a string into a DateTime. 尝试将字符串转换为DateTime时,我不断收到错误消息。

Error:
String was not recognized as a valid DateTime.

The string I'm trying to convert is gotten from a DataTable. 我要转换的字符串是从DataTable获取的。 Odd thing is, if I use just the date by itself and put it in a string, there's no error. 奇怪的是,如果我仅使用日期本身并将其放在字符串中,就没有错误。 The error only comes up when I get the date from the table. 仅当我从表格中获取日期时才会出现错误。

This is the date that is giving my trouble: 2008-04-20T07:00:00Z 这是给我带来麻烦的日期:2008-04-20T07:00:00Z

Here is my code: 这是我的代码:

string dateString = "2008-04-20T07:00:00Z";

foreach (DataRow dr in tblData.Rows)
{
        string tblDate = dr["DOCUMENTDATE"].ToString();
        string format = "yyyy-MM-ddTHH:mm:ssZ";

        DateTime convertDate = DateTime.ParseExact(tblDate, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
        //DateTime convertDate = DateTime.Parse(dateString);
        dr["DOCUMENTDATE"] = convertDate.ToString();
    }

I've looked up other posts and tried Parse, ParseExact, Convert.ToDateTime and still get the same error. 我查找了其他帖子,并尝试了Parse,ParseExact,Convert.ToDateTime,但仍然收到相同的错误。

EDIT 1: 编辑1:

The data type for dr["DOCUMENTDATE"] is a string. dr [“ DOCUMENTDATE”]的数据类型是字符串。 The data filling the table is gotten from a json that is converted into xml. 填充表的数据是从转换为xml的json中获取的。 I then used XMLtoDataTable. 然后,我使用了XMLtoDataTable。

What am I doing wrong? 我究竟做错了什么?

Here, try this. 在这里,尝试一下。 I think the problem is that you're not providing a recognizable format: 我认为问题在于您没有提供可识别的格式:

Relevant fiddle: https://dotnetfiddle.net/u1IoNX 相关提琴: https : //dotnetfiddle.net/u1IoNX

    string format = "yyyy-MM-ddTHH:mm:ssZ";
    string tblDate = dr["DOCUMENTDATE"].ToString(format);


    DateTime convertDate = DateTime.ParseExact(tblDate, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
    dr["DOCUMENTDATE"] = convertDate.ToString(format);

EDIT 编辑

From the documentation: 从文档中:

https://msdn.microsoft.com/en-us/library/ms131038(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/ms131038(v=vs.110).aspx

The DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) method parses the string representation of a date, which must be in a format defined by the format parameter. DateTime.ParseExact(String,String,IFormatProvider,DateTimeStyles)方法解析日期的字符串表示形式,该日期的格式必须为format参数定义的格式。

If I use your datestring example above, I do not get any errors. 如果使用上面的datestring示例,则不会出现任何错误。 Your date may look correct in the debugger, but I do not believe that it is formatting exactly as it should to match your specified format. 您的日期在调试器中可能看起来正确,但是我认为它的格式不完全符合您指定的格式。

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

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