TimeSpan.Parse of string including days dd-hh:mm:ss

921 Views Asked by At

The time span I want to parse is of the format dd-hh:mm:ss
It is the output by the Linux command that returns how long a process has been running.

Example:

string s = "5-15:10:20"; // 5 days 15h 10m 20s
TimeSpan.Parse(s);

This generates the error

System.FormatException was unhandled
Message="Input string was not in a correct format."
Source="mscorlib"
StackTrace:
   at System.TimeSpan.StringParser.Parse(String s)
   at System.TimeSpan.Parse(String s)

Important note: Code to be written in .net Framework 2.0
Is there a way to let the TimeParse correctly identify the first date part?

Edit: I tried replacing the - with : but it gives the same error.

3

There are 3 best solutions below

0
ojonasplima On BEST ANSWER

The problem with your string is that the char "-" is a optional minus sign, which indicates a negative TimeSpan. So, you have to use the Replace() method before parsing your string.

On this link you can see all the common chars that works with that method. For that, something like that will work:

string s = "5-15:10:20"; // 5 days 15h 10m 20s
TimeSpan.Parse(s.Replace('-', '.'));
1
Caius Jard On

This works for me:

TimeSpan.Parse(s.Replace('-', '.'));

As does this:

TimeSpan.ParseExact(s, @"d\-hh\:mm\:ss", null);

For more info on the format strings you can use, see the manual.. They're subtly different to DateTime format strings

1
MK-NEUKO On

I think that "-" is definitely the wrong sign. The "-" is for specifying a negative TimeSpan Since you've tried the ":" shin, give it a try with a "." at this point.

The "." is the official symbol to separate the day from the hours.