Created
October 30, 2012 14:49
-
-
Save anonymous/3980647 to your computer and use it in GitHub Desktop.
Timespan extension (used for log)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string ToReadableString(this TimeSpan timeSpan) | |
{ | |
var sb = new StringBuilder(16); | |
var isNeg = timeSpan.Ticks < 0; | |
if (isNeg) | |
{ | |
timeSpan = new TimeSpan(-timeSpan.Ticks); | |
} | |
var totalMilliseconds = timeSpan.TotalMilliseconds; | |
var hasMilliseconds = timeSpan.Milliseconds != 0; | |
var writeSeconds = timeSpan.Seconds != 0 || (hasMilliseconds && timeSpan.Minutes != 0); | |
if (totalMilliseconds >= 1000) | |
{ | |
if (timeSpan.Days != 0) | |
{ | |
sb.AppendFormat("{0}d ", timeSpan.Days); | |
} | |
var hasHours = timeSpan.Hours != 0; | |
if (hasHours) sb.AppendFormat("{0}h", timeSpan.Hours); | |
var b2 = timeSpan.Minutes != 0 || (timeSpan.Seconds != 0 && hasHours); | |
if (b2) | |
{ | |
sb.AppendFormat(hasHours ? ":{0:00}" : "{0}m", timeSpan.Minutes); | |
} | |
if (writeSeconds) | |
{ | |
if (hasHours || b2) | |
{ | |
sb.AppendFormat(":{0:00}", timeSpan.Seconds); | |
} | |
else | |
{ | |
sb.Append(timeSpan.Seconds); | |
} | |
} | |
} | |
var putMilliseconds = hasMilliseconds || sb.Length == 0; | |
if (putMilliseconds) | |
{ | |
if (sb.Length == 0) | |
{ | |
sb.AppendFormat("{0:0.###}", totalMilliseconds); | |
} | |
else | |
{ | |
sb.AppendFormat(writeSeconds ? ".{0:000}" : "{0:n0}", timeSpan.Milliseconds); | |
} | |
} | |
if (writeSeconds) | |
{ | |
sb.Append("s"); | |
} | |
else if (putMilliseconds) | |
{ | |
sb.Append("ms"); | |
} | |
if (isNeg) | |
{ | |
sb.Insert(0, "-"); | |
} | |
return sb.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment