Click here to Skip to main content
16,018,938 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I am trying to parse string to timespan but i m getting the error {"String was not recognized as a valid TimeSpan."}
My code is:
public string timeconvert(string grace, string difftime)
{
string totalTime;
TimeSpan t1 = TimeSpan.Parse(difftime);// here come the error
//In difftime value comes from function like 9.30 ,i thinks that's y it showing error.

if (string.IsNullOrEmpty(grace))
grace = "0";

TimeSpan g1 = TimeSpan.Parse(grace);
TimeSpan TotalTime = t1 + g1;
totalTime = TotalTime.ToString();


return totalTime;
}
// i m calling this function
item.ATT_TOTAL_ATT = timeconvert(Convert.ToString(item.ATT_BIOIN_GRACE), (Convert.ToString(item.ATT_DIFF_TIME)));

What I have tried:

{"String was not recognized as a valid TimeSpan."}
Posted
Updated 13-Apr-17 1:23am

It depends on the formats and units used by your strings.

Because it seems to be a floating point value, convert it to double first:
C#
double diff = Convert.ToDouble(difftime);
Depending on the unit pass the value to the TimeSpan object (here for seconds):
C#
TimeSpan t1 = TimeSpan.FromSeconds(diff);
Similar for the grace value.

[EDIT]
I missed how your function is called.
Change the function to accept doubles instead of strings and call it with the values:
C#
item.ATT_TOTAL_ATT = timeconvert(item.ATT_BIOIN_GRACE, item.ATT_DIFF_TIME);
This avoids the unnecessary conversions to string and back to double.

Or just make the calculation inline:
C#
item.ATT_TOTAL_ATT = TimeSpan.FromSeconds(item.ATT_BIOIN_GRACE + item.ATT_DIFF_TIME).ToString();
[/EDIT]
 
Share this answer
 
v2
Quote:
i thinks that's y it showing error.

Stop thinking, make sure! Use the debugger to inspect variables at error place.

When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900