Home > database >  I am trying to find a way to convert a TimeSpan variable into a integer amount of seconds
I am trying to find a way to convert a TimeSpan variable into a integer amount of seconds

Time:10-27

I am currently using a stopwatch in my C# program that is stored as a TimeSpan variable. How could I convert the data stored in that variable to be a rounded number of seconds stored as an integer?

CodePudding user response:

It sounds like the TimeSpan.TotalSeconds property is what you need here:

Gets the value of the current TimeSpan structure expressed in whole and fractional seconds.

You could use this property along with the Math.Round method and do something like this (assuming ts is your TimeSpan variable):

int seconds = (int)Math.Round(ts.TotalSeconds);

Note that since Math.Round returns a double, you'll still need to cast the result in order to end up with an int.

  • Related