C
C#•2y ago
Cryy

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 ? Thanks
13 Replies
mtreit
mtreit•2y ago
01:02:01 is hours:minutes:seconds
Cryy
Cryy•2y ago
So there is no way to parse tris string in the way I need ? *this except for doing it manually 🙂
mtreit
mtreit•2y ago
Actually with parse exact I think there is a format that should work
mtreit
mtreit•2y ago
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.
mtreit
mtreit•2y ago
Looks like maybe "c" instead of "dd" ? I'm on my phone so can't try it
mtreit
mtreit•2y ago
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.
mtreit
mtreit•2y ago
Looks like "d" without leading zeroes will work Can you remove leading zeroes from the days part?
Cryy
Cryy•2y ago
in inputString ?
mtreit
mtreit•2y ago
Yes
Cryy
Cryy•2y ago
probably. But guess it wont work. I tried it now in debug
mtreit
mtreit•2y ago
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.
mtreit
mtreit•2y ago
Pass zeroes for seconds and milliseconds
Cryy
Cryy•2y ago
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 🙂
Want results from more Discord servers?
Add your server
More Posts