- Home /
String format to show float as time
Hey, I'm making something that tracks time where it needs to be shown in the format as a chronometer so 00:00:00 or mm:ss:msms
I'm tracking time with a float, but I'm not sure what the string format to show it like that is, from what I've seen I've found something like this string.Format("{0}:{1:00}", time / 60, time % 60);, but it doesn't work as well as I'd hope.
What would the proper format be?
Answer by Hellium · Mar 04, 2018 at 10:12 AM
Supposing time
is in milliseconds:
public string FormatTime( float time )
{
int minutes = (int) time / 60000 ;
int seconds = (int) time / 1000 - 60 * minutes;
int milliseconds = (int) time - minutes * 60000 - 1000 * seconds;
return string.Format("{0:00}:{1:00}:{2:000}", minutes, seconds, milliseconds );
}
void Start()
{
Debug.Log( FormatTime( 79230 ) ) ; // Outputs 01:19:230
}
Supposing time
is in seconds:
public string FormatTime( float time )
{
int minutes = (int) time / 60 ;
int seconds = (int) time - 60 * minutes;
int milliseconds = (int) (1000 * (time - minutes * 60 - seconds));
return string.Format("{0:00}:{1:00}:{2:000}", minutes, seconds, milliseconds );
}
void Start()
{
Debug.Log( FormatTime( 79.230 ) ) ; // Outputs 01:19:230
}
Answer by fafase · Mar 04, 2018 at 10:31 AM
It'd be easier to use DateTime.
Get it on start and stote it. Then anytime you want to know how long has it been
DateTime.Now - startTime;
Then you can format that easily with ToString.
Answer by itsjustoneguy · Feb 24 at 04:51 PM
If you are using real world time. You should use the System.DateTime class. It has functions which can make all of this far easier. That way you don't have to manual calculate time. I made a video that may help https://youtu.be/XTtLKpA1FGc
Your answer
Follow this Question
Related Questions
How to convert timer to minutes, seconds and cents 3 Answers
how to Format time float (days/hours/minutes/seconds) 1 Answer
Multiple Cars not working 1 Answer
System.DateTime truncate Milliseconds 1 Answer
Distribute terrain in zones 3 Answers