Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert seconds to HH:MM:SS with String.Format

Tags:

c#

timespan

I have a float that is an amount of seconds, I want to make a string in the format hh:mm:ss that represent a countdown from 24hours. I'm trying to use this code:

TimeToMissionsReady = 86400f - FromMissionCompletedSeconds;
TimeToMissionsReadyString = string.Format ("{0:00}:{1:00}:{2:00}", TimeToMissionsReady / 3600f, (TimeToMissionsReady / 60f) % 60f, TimeToMissionsReady % 60f);

Debug.Log (TimeToMissionsReadyString);

but it isn't working 'cause it shows weird stuff like: 24:60:30 and after a second 24:59:29

Am I doing something wrong?

like image 575
Pitagora Avatar asked Dec 25 '22 07:12

Pitagora


1 Answers

You didn't even told us what is the type and value of TimeToMissionsReady exactly and I don't understand the meaning of 24:60:30 and after a second 24:59:29 sentence but the right way to solve your problem seems to using TimeSpan structure in in .NET Framework.

Let's say your TimeToMissionsReady is 86300 as a float.

float TimeToMissionsReady = 86300f;

You can use TimeSpan.FromSeconds(double) method to calculate those value.

TimeSpan ts = TimeSpan.FromSeconds(TimeToMissionsReady);

enter image description here

And you can format it with Custom TimeSpan Format Strings like;

Debug.Log(ts.ToString("hh\\:mm\\:ss")); // 23:58:20
like image 103
Soner Gönül Avatar answered Jan 09 '23 03:01

Soner Gönül