TimeSpanExt.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using Quadarax.Foundation.Core.Value.Formatters;
  2. namespace Quadarax.Foundation.Core.Value.Extensions
  3. {
  4. public static class TimeSpanExt
  5. {
  6. public static string ToReadableString(this TimeSpan owner)
  7. {
  8. // formats and its cutoffs based on TotalSeconds
  9. var cutoff = new SortedList<long, string> {
  10. {59, "{3:S}" },
  11. {60, "{2:M}" },
  12. {60*60-1, "{2:M}, {3:S}"},
  13. {60*60, "{1:H}"},
  14. {24*60*60-1, "{1:H}, {2:M}"},
  15. {24*60*60, "{0:D}"},
  16. {Int64.MaxValue , "{0:D}, {1:H}"}
  17. };
  18. // find nearest best match
  19. var find = cutoff.Keys.ToList()
  20. .BinarySearch((long)owner.TotalSeconds);
  21. // negative values indicate a nearest match
  22. var near = find<0?Math.Abs(find)-1:find;
  23. // use custom formatter to get the string
  24. return String.Format(
  25. new HmsFormatter(),
  26. cutoff[cutoff.Keys[near]],
  27. owner.Days,
  28. owner.Hours,
  29. owner.Minutes,
  30. owner.Seconds);
  31. }
  32. }
  33. }