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

StringToTimeSpan

Converts a string to a timespan

Source

/// <summary>
/// Converts a string time to a timespan.
/// </summary>
/// <param name="time">The time.</param>
/// <returns>
/// A timespan object.
/// </returns>
public static TimeSpan StringToTimeSpan(this string time)
{
    TimeSpan timespan;
    var result = TimeSpan.TryParse(time, out timespan);
    return result ? timespan : new TimeSpan(0, 0, 0);
}

Example

string s = "22:03:34";

// Returns a TimeSpan object with 22 Hours, 3 Minutes and 34 Seconds
TimeSpan ts = s.StringToTimeSpan();

Author: K M Thomas

Submitted on: 25 mrt. 2016

Language: C#

Type: System.String

Views: 4353