TimeSpanExt.cs 1.2 KB

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