How to Format a Time String with C# in Unity 3D

18 Oct 2010
Posted by xeophin

(This is only here for personal reference, since this is rather basic programming …)

/// <summary>
/// Formats the input string (in seconds) as a human readable 
/// string in the form of MM:SS.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> of the current playing time.
/// </returns>
private string formatedTimeString (string input) {
    int seconds;
    int minutes;
 
    minutes = Mathf.FloorToInt(input / 60);
    seconds = Mathf.FloorToInt(input - minutes * 60);
    string r = (minutes < 10) ? "0" + minutes.ToString() : minutes.ToString();
    r += ":";
    r += (seconds < 10) ? "0" + seconds.ToString() : seconds.ToString();
    return r;
}
(This is only here for personal reference, since this is rather basic programming …)/// /// Formats the input string (in seconds) as a human readable /// string in the form of MM:SS./// /// /// A of the current playing time./// private string formatedTimeString (string input) { int seconds; int minutes; minutes = Mathf.FloorToInt(input / 60); seconds = Mathf.FloorToInt(input - minutes * 60); string r = (minutes < 10) ? "0" + minutes.ToString() : minutes.ToString(); r += ":"; r += (seconds < 10) ? "0" + seconds.ToString() : seconds.ToString(); return r;}

Actually, a nicer way of

Actually, a nicer way of doing your time formatting once you have determined minutes and seconds is this:

return string.Format("{0:0}:{1:00}", minutes, seconds);

This will give you times in the format 0:00, e.g. 3:23 or 0:50 or 12:23. If you prefer the format 00:00 (as you do in your code), it would be:

return string.Format("{00:0}:{1:00}", minutes, seconds);

This will give you e.g. 03:23 or 00:50 or 12:23.


Hm, guess I have to try that

Hm, guess I have to try that out at some point.


Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
By submitting this form, you accept the Mollom privacy policy.


Navigation



Languages