TimeSpan “pretty time” format in C#

后端 未结 3 886
小蘑菇
小蘑菇 2021-01-01 15:09

Typing in the title to this question brought me to this question. I\'m looking for the same thing, but something perhaps less statically formatted if you get what I mean?

3条回答
  •  独厮守ぢ
    2021-01-01 15:28

    And if you care about pluralization:

    public static string ToPrettyFormat(this TimeSpan span) {
    
        if (span == TimeSpan.Zero) return "0 minutes";
    
        var sb = new StringBuilder();
        if (span.Days > 0)
            sb.AppendFormat("{0} day{1} ", span.Days, span.Days > 1 ? "s" : String.Empty);
        if (span.Hours > 0)
            sb.AppendFormat("{0} hour{1} ", span.Hours, span.Hours > 1 ? "s" : String.Empty);
        if (span.Minutes > 0)
            sb.AppendFormat("{0} minute{1} ", span.Minutes, span.Minutes > 1 ? "s" : String.Empty);
        return sb.ToString();
    
    }
    

提交回复
热议问题