- Home /
How can I make a timer follow the format 00:00 (Minutes, Seconds)
Hello!
I am making a timer for my game, and I want it to follow the format of 00:00.
The code I am using means that 5m 4s, or similar, comes up as 5:4, and I want it to come up as 05:04. If anyone knows how to fix this please let me know! Thanks!
void Update () {
float t = Time.time - StartTime;
string minutes = ((int)t / 60).ToString();
string seconds = (t % 60).ToString("f0");
TimerText.text = minutes + ":" + seconds;
}
}
Answer by theterrificjd · Dec 25, 2017 at 08:51 AM
Timer.text = string.Format("{0:0}:{1:00}s",minutes,seconds);
should do it I think.
{0:0} the first 0, before the :, is the first argument you pass after the string (ie: minutes). The second 0, after the :, is a formatting tool saying this can only be one integer into a string here. The first integer being the only integer you want, this works.
{1:00} is similar, but gets the second argument and gets the first two integer chars.
You can also pass your arguments as an array if you have many.
void Update () {
float t = Time.time - StartTime;
float minutes = (t / 60);
float seconds = (t % 60);
Timer.text = string.Format("{0:00}:{1:00}",minutes,seconds);
}
Answer by Chessnutter · Dec 25, 2017 at 08:56 AM
Sorry, but it doesn't work. It just adds milliseconds and an 'S' on the end, neither of which I want :( Thanks for trying though
For this method, your $$anonymous$$utes and seconds can't be strings, by the way, they'd need to be changed to floats (just change the declaration and remove the ToString, as the string.Format is a more reliable way to turn floats or integers into strings.
Ok, that works reasonably well, except when the timer hits 60 seconds it actually displays 0:60, then goes to 1:01. Is there a fix for this? Thanks!
Sorry for late reply. It is because it is a float, and it's rounding upwards I believe. What you want is to round it down.
seconds = $$anonymous$$athf.Floor(t % 60);
$$anonymous$$athf.Floor will round down to the nearest integer, where as $$anonymous$$athf.Ceil will round up. This should solve it, if not, you may need to sloppily add a -1 somewhere.
https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings
It's also possible that {0:D2} may be what you want. This list is definitely worth bookmarking though, as string.Format is very useful.