String was not recognized as a valid parameter for

2019-09-06 23:13发布

问题:

I'm using this code:

var sec = "163516";
TimeSpan time = TimeSpan.FromSeconds(double.Parse(sec));
DateTime butikDatetime = DateTime.Today.Add(time);
string dateTime = butikDatetime.ToString("dd-MM-yy HH:mm:ss");
DateTime date = DateTime.ParseExact(dateTime, "dd-MM-yy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

But receive this error for ParseExact:

Additional information: String was not recognized as a valid DateTime.

Somebody have an idea what is wrong?

回答1:

You are converting the butikDateTime to dateTime object without culture (framework will use the current thread culture) and later reconverting the using Invariant culture. Can you use Invariant culture while converting butikDateTime to string

var sec = "163516";
TimeSpan time = TimeSpan.FromSeconds(double.Parse(sec));
DateTime butikDatetime = DateTime.Today.Add(time);
string dateTime = butikDatetime.ToString("dd-MM-yy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
DateTime date = DateTime.ParseExact(dateTime, "dd-MM-yy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

Updated line 3 as :

string dateTime = butikDatetime.ToString("dd-MM-yy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);