How do I convert a TimeSpan to a formatted string?

This question already has an answer here:

  • How can I String.Format a TimeSpan object with a custom format in .NET? 18 answers
  • Timespan formatting [duplicate] 5 answers

  • Would TimeSpan.ToString() do the trick for you? If not, it looks like the code sample on that page describes how to do custom formatting of a TimeSpan object.


    I just built a few TimeSpan Extension methods. Thought I could share:

    public static string ToReadableAgeString(this TimeSpan span)
    {
        return string.Format("{0:0}", span.Days / 365.25);
    }
    
    public static string ToReadableString(this TimeSpan span)
    {
        string formatted = string.Format("{0}{1}{2}{3}",
            span.Duration().Days > 0 ? string.Format("{0:0} day{1}, ", span.Days, span.Days == 1 ? String.Empty : "s") : string.Empty,
            span.Duration().Hours > 0 ? string.Format("{0:0} hour{1}, ", span.Hours, span.Hours == 1 ? String.Empty : "s") : string.Empty,
            span.Duration().Minutes > 0 ? string.Format("{0:0} minute{1}, ", span.Minutes, span.Minutes == 1 ? String.Empty : "s") : string.Empty,
            span.Duration().Seconds > 0 ? string.Format("{0:0} second{1}", span.Seconds, span.Seconds == 1 ? String.Empty : "s") : string.Empty);
    
        if (formatted.EndsWith(", ")) formatted = formatted.Substring(0, formatted.Length - 2);
    
        if (string.IsNullOrEmpty(formatted)) formatted = "0 seconds";
    
        return formatted;
    }
    

    通过将其转换为日期时间,您可以获得本地化的格式:

    new DateTime(timeSpan.Ticks).ToString("HH:mm");
    
    链接地址: http://www.djcxy.com/p/18502.html

    上一篇: 格式化否定的TimeSpan

    下一篇: 如何将TimeSpan转换为格式化的字符串?