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?

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
}

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.

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 How to format time in unity (Unity Tutorial) - YouTube