Skip to content

Instantly share code, notes, and snippets.

@Code0987
Created October 28, 2012 13:29
Show Gist options
  • Select an option

  • Save Code0987/3968602 to your computer and use it in GitHub Desktop.

Select an option

Save Code0987/3968602 to your computer and use it in GitHub Desktop.
/// <summary>
/// Formats the time to user safe string.
/// </summary>
/// <param name="ts">The ts.</param>
/// <param name="shorthand">if set to <c>true</c> [shorthand].</param>
/// <returns></returns>
public static string ToFriendlyString1(this TimeSpan ts, bool shorthand)
{
if(ts == TimeSpan.MaxValue || ts == TimeSpan.MinValue)
return "Sometime";
StringBuilder sb = new StringBuilder();
if(!shorthand)
{
if((int)ts.Days == 365.0 || (int)ts.Days == 366.0) sb.Append("1 year, ");
else if(ts.Days > 365.0) sb.Append((int)(ts.Days / 365.0) + " years, ");
else if(ts.Days == 1.0) sb.Append("1 day, ");
else if(ts.Days > 1.0) sb.Append((int)ts.Days + " days, ");
if(ts.Hours == 1.0) sb.Append("1 hour, ");
else if(ts.Hours > 1.0) sb.Append((int)ts.Hours + " hours, ");
if(ts.Minutes == 1.0) sb.Append("1 minute, ");
else if(ts.Minutes > 1.0) sb.Append((int)ts.Minutes + " minutes, ");
if(ts.Seconds == 1.0) sb.Append("1 second, ");
else if(ts.Seconds > 1.0) sb.Append((int)ts.Seconds + " seconds, ");
}
else
{
if((int)ts.Days == 365.0 || (int)ts.Days == 366.0) sb.Append("1yr, ");
else if(ts.Days > 365.0) sb.Append((int)(ts.Days / 365.0) + "yr, ");
else if(ts.Days == 1.0) sb.Append("1d, ");
else if(ts.Days > 1.0) sb.Append((int)ts.Days + "d, ");
if(ts.Hours == 1.0) sb.Append("1h, ");
else if(ts.Hours > 1.0) sb.Append((int)ts.Hours + "h, ");
if(ts.Minutes == 1.0) sb.Append("1min, ");
else if(ts.Minutes > 1.0) sb.Append((int)ts.Minutes + "min, ");
if(ts.Seconds == 1.0) sb.Append("1s, ");
else if(ts.Seconds > 1.0) sb.Append((int)ts.Seconds + "s, ");
}
sb.Remove(sb.Length - 2, 2);
return sb.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment