Reputation: 173
I need to convert my string to time span in c#, Here is my string 52:13:27.0000000
When I am trying Timespan.parse it is giving error
The TimeSpan could not be parsed because at least one of the numeric components is out of range or contains too many digits.
Please help! Thanks
Upvotes: 8
Views: 10323
Reputation: 2835
Timespan.parse is giving error because it takes can't take
hours>23
minutes>59
seconds>59
/*Parsing string format with above conditions "hh:mm:ss:miliseconds"*/
Timespan.parse("hh:mm:ss:miliseconds");
in this format you won't get Exception
string str = "52:13:27.0000000";
int hours = Convert.ToInt32(str.Substring(0,2));
int minutes = Convert.ToInt32(str.Substring(3, 2));
int seconds = Convert.ToInt32(str.Substring(6, 2));
string miliseconds= (str.Substring(str.IndexOf('.')+1,str.Length-str.IndexOf('.')-1));
TimeSpan sp = TimeSpan.FromHours(hours);
TimeSpan interval = TimeSpan.Parse(sp .Days+ ":"+sp.Hours+":"+minutes+":"+seconds+"."+
miliseconds);
Upvotes: 0
Reputation: 1784
TimeSpan.Parse()
accepts Days:Hours:Minutes:Seconds:Miliseconds
if you want to have more than 24 hours, you have to add a day.
In your specific case, it should be something like the following:
TimeSpan.Parse("2:04:13:27.0000000");
Upvotes: 11
Reputation: 3875
What you can do is convert the hours into days by doing:
string x = "52:13:27.000";
TimeSpan ts = new TimeSpan(int.Parse(x.Split(':')[0]), // hours
int.Parse(x.Split(':')[1]), // minutes
int.Parse(x.Split(':')[2].Split('.')[0] ) // seconds
);
Desired Output:
Upvotes: 3