ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

TimeSpan ToHumanTimeString

Light-weight extension to output time. If you need additional human readable strings

Source

/// <summary>
/// Converts <see cref="TimeSpan"/> objects to a simple human-readable string.  Examples: 3.1 seconds, 2 minutes, 4.23 hours, etc.
/// </summary>
/// <param name="span">The timespan.</param>
/// <param name="significantDigits">Significant digits to use for output.</param>
/// <returns></returns>
public static string ToHumanTimeString(this TimeSpan span, int significantDigits = 3)
{
    var format = "G" + significantDigits;
    return span.TotalMilliseconds < 1000 ? span.TotalMilliseconds.ToString(format)  + " milliseconds"
        : (span.TotalSeconds < 60 ? span.TotalSeconds.ToString(format)             + " seconds"
            : (span.TotalMinutes < 60 ? span.TotalMinutes.ToString(format)           + " minutes"
                : (span.TotalHours < 24 ? span.TotalHours.ToString(format)           + " hours"
                                        : span.TotalDays.ToString(format)           + " days")));
}

Example

var stopwatch = new StopWatch();
stopwatch.Start();
Thread.Sleep(10000);
stopwatch.Stop();
Debug.WriteLine("That just took {0}", stopwatch.Elapsed.ToHumanTimeString());

Author: Greg Wilson

Submitted on: 27 mrt. 2015

Language: C#

Type: TimeSpan

Views: 10235