简体   繁体   中英

date time parse error

I'm using .net Framework 4.0 and developing an console app.

My regional setting are set as en-us.

I'm getting error:

String was not recognized as a valid DateTime.

on following code.

DateTime time = XmlConvert.ToDateTime("2013-11-08T08:08:32+5.5", "yyyy-M-dTH:m:sz");

I'm testing my app in windows 2008 R2 server.

Your code does not account for the .5 bit ( z takes care just of the +5 part without decimals). Corrected version:

DateTime time = XmlConvert.ToDateTime("2013-11-08T08:08:32+5.5", "yyyy-M-dTH:m:sz.f");

UPDATE

As rightly pointed out by digEmAll via comments, the proposed .f correction avoids the problem although does not account for the date properly. The .f modifier refers always to a fraction of second, even in case of being located far away from seconds (as in this case). The fractions of z have to be provided by relying on the : modifier and by converting z into zzz .

Thus, the aforementioned code represents a practical solution for the OP's conditions (technically speaking, taking a wrong date format as inputs), although does not deliver an accurate result. A pre-modification of the input format would be required in order to accomplish so, that is:

string input = "2013-11-08T08:08:32+5.5";
string format = "yyyy-M-dTH:m:sz";
string correctedInput = input;
string correctedFormat = format;
string[] temp = input.Split('.');
if (temp.Length == 2 && temp[1].AsEnumerable().Select(x => char.IsDigit(x)).Count() == temp[1].Length)
{
    correctedInput = temp[0] + ":" + Convert.ToString(Math.Round(60 * Convert.ToDecimal(temp[1]) / 10, 2));
    correctedFormat = "yyyy-M-dTH:m:szzz";
}
DateTime time = XmlConvert.ToDateTime(correctedInput, correctedFormat);

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