简体   繁体   中英

String was not recognized as a valid parameter for DateTime.ParseExact

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?

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);

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