开发者

What is wrong with this TimeSpan.ParseExact line?

开发者 https://www.devze.com 2023-02-22 18:05 出处:网络
I am receiving a FormatError exception from this call to TimeSpan.ParseExact, but the MSDN documentation that I am reading says that this format should be correct:

I am receiving a FormatError exception from this call to TimeSpan.ParseExact, but the MSDN documentation that I am reading says that this format should be correct:

TimeSpan timeSpan = TimeSpan.ParseExact("172100", "HHmmss", CultureInfo.InvariantCultur开发者_JS百科e);

Can someone please tell me why this is not working? I am doing almost exactly the same thing with a call to DateTime.ParseExact and this works fine:

DateTime datetTime = DateTime.ParseExact("090820", "yyMMdd", CultureInfo.InvariantCulture);


TimeSpan does not use the same formatting rules as DateTime.

You want hhmmss, not HHmmss.

You're looking at the wrong page in MSDN - you want something like:

http://msdn.microsoft.com/en-us/library/se73z7b9.aspx


With ref to this more accurate documentation: http://msdn.microsoft.com/en-us/library/ee372287.aspx

You need to use hh for hours, not HH.


As per Custom TimeSpan Format Strings, hours are represented by "h" rather than "H".

So this works fine:

TimeSpan timeSpan = TimeSpan.ParseExact("172100", "hhmmss", 
                                        CultureInfo.InvariantCulture);

The documentation you linked to is for custom date and time format strings, which aren't the same. They're for DateTime.ParseExact etc; the documentation I linked to is for TimeSpan.ParseExact etc.


Parse the string to a DateTime value, then subtract it's Date value to get the time as a TimeSpan:

DateTime t = DateTime.ParseExact("172100", "HHmmss", CultureInfo.InvariantCulture);
TimeSpan time = t - t.Date;


You are try to use DateTime format strings to parse a TimeSpan. TimeSpan has its own (slightly different) format strings. See MSDN for a complete listing: Custom TimeSpan Format Strings

In particular, change HH to hh. This will give you:

TimeSpan timeSpan = TimeSpan.ParseExact("172100",
                                        "hhmmss", // Note this parameter
                                        CultureInfo.InvariantCulture);
0

精彩评论

暂无评论...
验证码 换一张
取 消