Parsing string to TimeSpan
Hey guys, I'm trying to parse some string to TimeSpan . Input string is "01:02:01" and I'm trying it to parse to TimeSpan structure like this
TimeSpan.ParseExact(inputString, "dd:hh:mm", CultureInfo.InvariantCulture)
(expecting days:hours:minutes) but I got "Input string was not in a correct format." exception. What I'm doing wrong ? Thanks13 Replies
01:02:01 is hours:minutes:seconds
So there is no way to parse tris string in the way I need ?
*this
except for doing it manually 🙂
Actually with parse exact I think there is a format that should work
TimeSpan.ParseExact Method (System)
Converts the string representation of a time interval to its TimeSpan equivalent. The format of the string representation must match a specified format exactly.
Looks like maybe "c" instead of "dd" ? I'm on my phone so can't try it
Standard TimeSpan format strings
Review standard TimeSpan format strings, which use a single format specifier to define the text representation of a TimeSpan value in .NET.
Looks like "d" without leading zeroes will work
Can you remove leading zeroes from the days part?
in inputString ?
Yes
probably. But guess it wont work. I tried it now in debug
Parse the string yourself into days, hours, minutes and then just use the TimeSpan constructor that takes days
https://learn.microsoft.com/en-us/dotnet/api/system.timespan.-ctor?view=net-6.0#system-timespan-ctor(system-int32-system-int32-system-int32-system-int32-system-int32)
TimeSpan Constructor (System)
Initializes a new instance of the TimeSpan structure.
Pass zeroes for seconds and milliseconds
Yeah I guess I need to do that that way. Thank you 🙂
@mtreit I did it manually and it worked. But than I was still trying to parse that in unit tests and I made it work like that:
var timeSpan = TimeSpan.ParseExact(inputString, "dd\\:hh\\:mm", CultureInfo.InvariantCulture);
. No idea why these backslashes are required but it works now 🙂