Created
May 19, 2013 05:44
-
-
Save spewu/5606813 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Text; | |
public static class TimeSpanExtensions | |
{ | |
/// <summary> | |
/// Returns a string containing the human readable version of this time span, i.e 4 days, 3 hours, 26 minutes and 13.4 seconds. | |
/// </summary> | |
/// <param name="timeSpan"></param> | |
/// <returns></returns> | |
public static string ToHumanText(this TimeSpan timeSpan) | |
{ | |
var sb = new StringBuilder(30); | |
if (timeSpan.Days > 0) | |
{ | |
sb.Append(timeSpan.Days); | |
sb.Append(timeSpan.Days == 1 ? " day" : " days"); | |
} | |
if (timeSpan.Hours > 0) | |
{ | |
if (sb.Length > 1) | |
{ | |
sb.Append(", "); | |
} | |
if (timeSpan.Minutes == 0 && timeSpan.Days > 0) | |
{ | |
sb.Append("and "); | |
} | |
sb.Append(timeSpan.Hours); | |
sb.Append(timeSpan.Hours == 1 ? " hour" : " hours"); | |
} | |
if (timeSpan.Minutes > 0) | |
{ | |
if (sb.Length > 0) | |
{ | |
sb.Append(", "); | |
} | |
if (timeSpan.Seconds == 0 && timeSpan.Hours > 0) | |
{ | |
sb.Append("and "); | |
} | |
sb.Append(timeSpan.Minutes); | |
sb.Append(timeSpan.Minutes == 1 ? " minute" : " minutes"); | |
} | |
if (timeSpan.Seconds > 0) | |
{ | |
if (sb.Length > 0) | |
{ | |
sb.Append(", "); | |
} | |
if (timeSpan.Minutes > 0) | |
{ | |
sb.Append("and "); | |
} | |
sb.Append(timeSpan.Seconds); | |
if (timeSpan.Milliseconds > 0) | |
{ | |
sb.Append("."); | |
sb.Append(timeSpan.Milliseconds); | |
} | |
if (timeSpan.Seconds == 1 && timeSpan.Milliseconds == 0) | |
{ | |
sb.Append(" second"); | |
} | |
else | |
{ | |
sb.Append(" seconds"); | |
} | |
} | |
if (timeSpan.Milliseconds > 0 && timeSpan.Seconds == 0) | |
{ | |
sb.Append(timeSpan.Milliseconds); | |
sb.Append(timeSpan.Milliseconds == 1 ? " millisecond" : " milliseconds"); | |
sb.Append(" ("); | |
sb.Append(timeSpan.Ticks); | |
sb.Append(" ticks)"); | |
} | |
return sb.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment