- Home /
How to format TimeSpan.ToString in .NET 4.0
Hello, I'm trying to format my TimeSpan string using
myString = myTimeSpan.ToString("c");
However the TimeSpan.ToString method does not take a format string as an argument until .NET 4.0 while Unity's version of Mono is still on 3.5.
How would you format DateTime and TimeSpan strings then?
Answer by whydoidoit · Jul 20, 2012 at 10:30 AM
myString = string.Format("{0:c}", myTimeSpan);
Thank you! However this solution works only for formatting DateTime.
In the case of TimeSpan, even if the format string is changed such as
myString = string.Format("{0:%s}", myTimeSpan);
which should only output the value of the myTimeSpan.Seconds property, myTimeSpan is still displayed with the default format string "c", showing dd:hh:mm:ss:fffffff.
So it doesn't seem to work for formatting TimeSpan.
So what format are you after? Something like this:
myString = string.Format("{0:00}:{1:00}", myTimeSpan.$$anonymous$$inutes, myTimeSpan.Seconds);
Yes! This is what I was looking for!
I had been using a workaround as such:
myString = string.Format("{0:HH\\:mm\\:ss}", new DateTime(myTimeSpan.Ticks));
but your solution is much more correct, thank you.
Answer by mindlube · Jul 21, 2012 at 03:39 AM
I would ask on stackoverflow
Stackoverflow is a great resource, but I personally find that Unity-centric questions get better answers here. Also this question is for an older version of C# and Stackoverflow tends to focus on the latest specification from my experience.
Your answer
![](https://koobas.hobune.stream/wayback/20220613074440im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
System.DateTime truncate Milliseconds 1 Answer
Help, getting ambiguous reference error 1 Answer
Help, getting ambiguous reference error 1 Answer
DateTime.ParseExact throws FormatException 0 Answers
Formatting Date and Time 3 Answers