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

TimeSpanToString

Converts a timespan to a string displaying hours and minutes

Source

/// <summary>
/// Converts the seconds to an hour \ min display string.
/// </summary>
/// <param name="timeSpan">The time span.</param>
/// <returns>
/// A string in the format x hours y mins.
/// </returns>
public static string TimeSpanToString(this TimeSpan timeSpan)
{
    var s = TimeSpan.FromSeconds(timeSpan.TotalSeconds);

    return string.Format("{0} hours {1} mins", (int)s.TotalHours, s.Minutes);
}

Example

TimeSpan ts = new TimeSpan(1, 6, 4, 34);

string display = ts.TimeSpanToString(); // 30 hours 4 mins

Author: K M Thomas

Submitted on: 25 mrt. 2016

Language: C#

Type: System.TimeSpan

Views: 4306