- Home /
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 :)
Answer by MaT227 · Jul 26, 2014 at 09:07 PM
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
Thank you very much for the help, I looked through the links you sent however I just kept on getting the error "No appropriate version of 'System.TimeSpan.ToString' for the argument list '(String)' was found." It did however give me the idea to approach it like this which seems to work but maybe not in the most optimal fashion, I am using unity script, im not sure if that is why it is returning an error? This is what I have ended up with:
timeleft = life1 - nowTime;
var formattedTimeLeft0 = timeleft.ToString();
var splitTimeFull = formattedTimeLeft0.Split(":"[0]);
var splitTime$$anonymous$$illi = splitTimeFull[2].Split("."[0]);
formattedTimeLeft = splitTimeFull[1] + ":" + splitTime$$anonymous$$illi[0];
Again thank you very much for the help.
Unfortunately I am not used to UnityScript and I can't help you further. :( If you found the solution yourself, I suggest you to post it as an answer and validate it and thumb up for helping answers.
Answer by BananaAcid · Oct 22, 2017 at 11:51 PM
just for anyone looking for something similar: i went with
private string toStr(TimeSpan t)
{
return t.Hours + ":" + t.Minutes + ":" + t.Seconds + "." + t.Milliseconds;
}
Your answer
Follow this Question
Related Questions
Subtract milliseconds from 12 hours? 1 Answer
Leader board which maintains different time zones ? 2 Answers
Serializing a Timespan 1 Answer
Best Practices: TimeSpans 1 Answer
Timespan to int total seconds 1 Answer