TimeSpanExt.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. if (owner == null)
  12. throw new ArgumentNullException(nameof(owner));
  13. // formats and its cutoffs based on TotalSeconds
  14. var cutoff = new SortedList<long, string> {
  15. {59, "{3:S}" },
  16. {60, "{2:M}" },
  17. {60*60-1, "{2:M}, {3:S}"},
  18. {60*60, "{1:H}"},
  19. {24*60*60-1, "{1:H}, {2:M}"},
  20. {24*60*60, "{0:D}"},
  21. {Int64.MaxValue , "{0:D}, {1:H}"}
  22. };
  23. // find nearest best match
  24. var find = cutoff.Keys.ToList()
  25. .BinarySearch((long)owner.TotalSeconds);
  26. // negative values indicate a nearest match
  27. var near = find<0?Math.Abs(find)-1:find;
  28. // use custom formatter to get the string
  29. return String.Format(
  30. new HmsFormatter(),
  31. cutoff[cutoff.Keys[near]],
  32. owner.Days,
  33. owner.Hours,
  34. owner.Minutes,
  35. owner.Seconds);
  36. }
  37. }
  38. }