简体   繁体   中英

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.

Error:
String was not recognized as a valid DateTime.

The string I'm trying to convert is gotten from a 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

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.

EDIT 1:

The data type for dr["DOCUMENTDATE"] is a string. The data filling the table is gotten from a json that is converted into xml. I then used 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

    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

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.

If I use your datestring example above, I do not get any errors. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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