Get Readable Timespan - CSharp System

CSharp examples for System:TimeSpan

Description

Get Readable Timespan

Demo Code

// License? CC BY-SA 3.0 - https://creativecommons.org/licenses/by-sa/3.0/legalcode
using System.Linq;
using System.Collections.Generic;
using System;//from w  w w. j  av  a2  s .com

public class Main{
        //
      // "How to produce ?human readable?? strings to represent a TimeSpan" by "rene" is licensed under CC BY-SA 3.0
      //
      // Title?   How to produce ?human readable?? strings to represent a TimeSpan
      // Author?  rene - http://stackoverflow.com/users/578411/rene
      // Source?  http://stackoverflow.com/a/21649465/298054
      // License? CC BY-SA 3.0 - https://creativecommons.org/licenses/by-sa/3.0/legalcode
      //
      public static string GetReadableTimespan(TimeSpan ts)
      {
         // Formats and its cutoffs based on totalseconds
         var cutoff = new SortedList<long, string> {
            { 60,            "{3:S}"                     },
            { 60 * 60,         "{2:M}, {3:S}"               },
            { 24 * 60 * 60,      "{1:H}, {2:M}, {3:S}"         },
            { Int64.MaxValue,   "{0:D}, {1:H}, {2:M}, {3:S}"   },
         };

         // Find nearest best match
         var find = cutoff.Keys.ToList().BinarySearch((long)ts.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]],
            ts.Days,
            ts.Hours,
            ts.Minutes,
            ts.Seconds);
      }
}

Related Tutorials