Formatting a DateTime.TimeSpan

Hi All, I am making a life timer that gives the user a life back after 15 minutes and so far the system is working well, I am now trying to display the time until a new life is given, I have saved the time the life will be given in PlayerPrefs and that works fine, also TimeSpan is almost a perfect solution apart from the fact that I am struggling to format it to only show the minutes:Seconds left not the days/hours/mins/sec/millisec is there anyway to format TimeSpan? I have looked through this site and also googled it but I cannot find a solution that actually works. My Code is as follows for getting the time span and I just use that in a GUI.Label

DateTime.TryParse(PlayerPrefs.GetString("Life1"), life1);
	nowTime = DateTime.UtcNow;
	timeleft = life1 - nowTime;

Sorry if this has been asked before and I have just missed the answer. I am new to unity so sorry if its a simple question!

Thanks in advance :slight_smile:

Here is a link that might help you to format TimeSpan : Standard TimeSpan Format Strings

And here is the complete list of the formatting possibilties of TimeSpan : Custom TimeSpan Format Strings

just for anyone looking for something similar: i went with

private string toStr(TimeSpan t)
{
    return t.Hours + ":" + t.Minutes + ":" + t.Seconds + "." + t.Milliseconds;
}

Hi,
For anyone encountering issue with timespan formatting, I think this is the easiest solution: var myText = myTimeSpan.ToString(@"mm\:ss"); // 12:06

Any other time component can be added based on normal .NET format as long as the non timespan component are escaped with a “\”.

var text1 = myTimeSpan.ToString(@"mm\:ss\.fff");    // 12:06.684
var text2 = myTimeSpan.ToString(@"HH\:mm");       // 05:12

More info: Custom TimeSpan format strings - .NET | Microsoft Learn