| 1234567891011121314151617181920212223242526272829303132333435363738 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using Quadarax.Foundation.Core.Value.Formatters;
- namespace Quadarax.Foundation.Core.Value.Extensions
- {
- public static class TimeSpanExt
- {
- public static string ToReadableString(this TimeSpan owner)
- {
- // formats and its cutoffs based on TotalSeconds
- var cutoff = new SortedList<long, string> {
- {59, "{3:S}" },
- {60, "{2:M}" },
- {60*60-1, "{2:M}, {3:S}"},
- {60*60, "{1:H}"},
- {24*60*60-1, "{1:H}, {2:M}"},
- {24*60*60, "{0:D}"},
- {Int64.MaxValue , "{0:D}, {1:H}"}
- };
- // find nearest best match
- var find = cutoff.Keys.ToList()
- .BinarySearch((long)owner.TotalSeconds);
- // negative values indicate a nearest match
- var near = find<0?Math.Abs(find)-1:find;
- // use custom formatter to get the string
- return String.Format(
- new HmsFormatter(),
- cutoff[cutoff.Keys[near]],
- owner.Days,
- owner.Hours,
- owner.Minutes,
- owner.Seconds);
- }
- }
- }
|