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 ?
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 ?
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 TimeSpan
s.
Though note that negative TimeSpan
s 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
.
12:34:45
, then escaping is not required. –
Peculiarity 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"
This works for me
"d'd:'h'h:'m'm:'s's'"
Found here http://msdn.microsoft.com/en-us/library/ee372287.aspx
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();
}
© 2022 - 2024 — McMap. All rights reserved.
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