Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeSpan.ToString() return string like (d:hh:mm:ss)

Tags:

c#

timespan

TimeSpan Ts = new TimeSpan(5, 4, 3, 2);
return Ts.ToString("?");

What expression should I replace with a question mark to get this format: 5d:4h:3m:2s ?

like image 557
Mosh Feu Avatar asked Mar 10 '13 12:03

Mosh Feu


3 Answers

TimeSpan timeSpan = new TimeSpan(5, 4, 3, 2);
string str = timeSpan.ToString(@"d\d\:h\h\:m\m\:s\s", System.Globalization.CultureInfo.InvariantCulture);

See Custom TimeSpan Format Strings on how to format TimeSpans.

Though note that negative TimeSpans cannot be distinguished from positive ones. They appear like they have been negated. Therefor -new TimeSpan(5,4,3,2) will still show as 5d:4h:3m:2s. If you want negative numbers to display, you should format your own numbers though the properties of TimeSpan.

like image 161
Caramiriel Avatar answered Oct 17 '22 17:10

Caramiriel


You can accomplish this by using your current code

TimeSpan Ts = new TimeSpan(5, 4, 3, 2);
var RetValue = string.Format("{0}d:{1}h:{2}m:{3}s",
    Ts.Days,
    Ts.Hours,
    Ts.Minutes,
    Ts.Seconds);

yields this as a formatted result "5d:4h:0m:2s"

like image 26
MethodMan Avatar answered Oct 17 '22 16:10

MethodMan


This works for me

"d'd:'h'h:'m'm:'s's'"

Found here http://msdn.microsoft.com/en-us/library/ee372287.aspx

like image 2
ojhawkins Avatar answered Oct 17 '22 18:10

ojhawkins