How to display int as a TimeSpan in string.Format?
-
16-06-2021 - |
Question
I have the following code:
int sec = 62;
string str = string.Format("Time: {0:xxx}", sec);
What should I type in the place of xxx
if I want an output like this: Time: 00:01:02
?
I know I can type:
string.Format("Time: {0:xxx}", TimeSpan.FromSeconds(sec));
or similar but the only part I can change is the xxx
part.
Any ideas?
Solution
Since the format string cannot change the type of its arguments there is no other option than the one you cannot use.
After all, int
is a type that contains numbers (fundamentally, at least), not time spans and thus why would an int
be formattable as a time span?
OTHER TIPS
You could do something like String.Format("Time: {0}", TimeSpan.FromSeconds(sec).ToString("c");
The exact format of the ToString
argument can be found at http://msdn.microsoft.com/en-us/library/dd992632.aspx
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow