43 lines
1.5 KiB
C#
43 lines
1.5 KiB
C#
using System;
|
|
using System.Runtime.Remoting.Messaging;
|
|
|
|
namespace LeafWeb.Core.Utility
|
|
{
|
|
public static class TimeSpanExtensions
|
|
{
|
|
public static string ToReadableString(this TimeSpan span)
|
|
{
|
|
Func<int, string> pluralize = i => i > 1 ? "s" : string.Empty;
|
|
var formatted = string.Format("{0}{1}{2}{3}",
|
|
span.Duration().Days > 0 ? $"{span.Days:0} day{pluralize(span.Days)}, " : string.Empty,
|
|
span.Duration().Hours > 0 ? $"{span.Hours:0} hour{pluralize(span.Hours)}, " : string.Empty,
|
|
span.Duration().Minutes > 0 ? $"{span.Minutes:0} minute{pluralize(span.Minutes)}, " : string.Empty,
|
|
span.Duration().Seconds > 0 ? $"{span.Seconds:0} second{pluralize(span.Seconds)}" : string.Empty);
|
|
|
|
if (formatted.EndsWith(", ")) formatted = formatted.Substring(0, formatted.Length - 2);
|
|
|
|
if (string.IsNullOrEmpty(formatted)) formatted = "0 seconds";
|
|
|
|
return formatted;
|
|
}
|
|
|
|
public static string ToRoundedReadableString(this TimeSpan span)
|
|
{
|
|
Func<int, string> pluralize = i => i > 1 ? "s" : string.Empty;
|
|
Func<int, string, string> formatTime = (i, s) => $"{i:0} {s}{pluralize(i)}";
|
|
if (span.Duration().Days > 90)
|
|
return formatTime(span.Days/30, "month");
|
|
if (span.Duration().Days > 0)
|
|
return formatTime(span.Days, "day");
|
|
if (span.Duration().Hours > 0)
|
|
return formatTime(span.Hours, "hour");
|
|
if (span.Duration().Minutes > 0)
|
|
return formatTime(span.Minutes, "minute");
|
|
if (span.Duration().Seconds > 0)
|
|
return formatTime(span.Seconds, "second");
|
|
|
|
return "0 seconds";
|
|
}
|
|
}
|
|
}
|