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

4

5
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 ?

Javanese answered 10/3, 2013 at 12:2 Comment(1)
you can accomplish this using your code and formatting 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.Milliseconds, Ts.Seconds);Opening
P
12
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.

Peculiarity answered 10/3, 2013 at 12:10 Comment(3)
There is no need to escape all characters of your format string. Escaping \. and \: is enough.Shantishantung
Mosh wanted parts postfixed with its corresponding part, so for his usecase its required. If you just want 12:34:45, then escaping is not required.Peculiarity
You are right. Sorry. I did not read the question the the very end.Shantishantung
O
3

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"

Opening answered 10/3, 2013 at 12:17 Comment(0)
D
2

This works for me

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

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

Diplostemonous answered 10/3, 2013 at 12:20 Comment(1)
This is incredibly helpful (especially in gridview). Thank you very much!Nephrectomy
C
0

Here's a TimeSpan Extension method that will hide empty large time parts.

public static string ToShortString(this TimeSpan Ts)
{
    if(Ts.TotalDays > 1d)
        return Ts.ToString("d'd:'h'h:'m'm:'s's'");

    if(Ts.TotalHours > 1d)
        return Ts.ToString("h'h:'m'm:'s's'");

    if(Ts.TotalMinutes > 1d)
        return Ts.ToString("m'm:'s's'");

    if(Ts.TotalSeconds > 1d)
        return Ts.ToString("s's'");

    if(Ts.TotalMilliseconds > 1d)
        return Ts.ToString("fffffff'ms'");

    return Ts.ToString();
}
Cobblestone answered 25/4, 2019 at 2:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.