简体   繁体   中英

Convert irregular strings to TimeSpan in C#

I have several strings in the format below:

"1:15"
":45"
"1:30:45"

I need them converted to a TimeSpan, but when I TimeSpan.Parse some of them (the first one, for example) it returns it as 1 hour and 15 minutes, where i would want it to be 1 minute and 15 seconds.

Any advice would be greatly appreciated!

You could use an overload of TimeSpan.ParseExact that allows you to specify an array of exact format specifiers .

var formats = new string[] {@"m\:s", @"\:s", ...};
var timeSpace = TimeSpan.ParseExact(input, formats, CultureInfo.CurrentCulture);

Note that ParseExact was introduced in .Net 4

The parameter string needs to be in the specific form specified below:

[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]

So "1:15" will be treated as hh:mm. If you are passing 1 min 15 seconds, you need to reformat your parameter string to be "00:01:15" . You can simply split your string to corresponding days, hour, min, ss variables and use those to assign your TimeSpan object.

MSDN has good documentation here:

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

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