Kyle
Kyle

Reputation: 13

Formatting a timer to mm:ss from seconds

I'm somewhat new to programming, but I have some knowledge in coding. I've been stuck for a few hours now trying different ways of doing this, seems straight-forward but I'm not getting a positive result. I would like a simple mm:ss format from a counter counting seconds. I've tried this:

if(instruct.activeSelf == false)
{
    timer += Time.deltaTime;
    string fmt = @"mm\:ss";
    timerText.text = "Time: " + timer.ToString(fmt);
}

And this:

if(instruct.activeSelf == false)
{
    timer += Time.deltaTime;
    TimeSpan ts = TimeSpan.FromSeconds(timer);
    timerText.text = "Time: " + ts.ToString();
}

This code is under the update class, after instructions I want the timer to start. Any help would be greatly appreciated.

Upvotes: 1

Views: 1164

Answers (1)

Guffa
Guffa

Reputation: 700900

If you use the format string with a TimeSpanvalue, it works:

if(instruct.activeSelf == false) {
  timer += Time.deltaTime;
  TimeSpan ts = TimeSpan.FromSeconds(timer);
  timerText.text = "Time: " + ts.ToString(@"mm\:ss");
}

Upvotes: 1

Related Questions