TimeSpan “pretty time” format in C#

后端 未结 3 872
小蘑菇
小蘑菇 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();
    
    }
    
    0 讨论(0)
  • 2021-01-01 15:34

    You can just output this directly:

     string result = string.Format("{0} days, {1} hours, {2} minutes", duration.Days, duration.Hours, duration.Minutes);
    

    If you are going to be handling "short" times, and you want this to be cleaner, you could do something like:

    public string PrettyFormatTimeSpan(TimeSpan span)
    {
        if (span.Days > 0)
             return string.Format("{0} days, {1} hours, {2} minutes", span.Days, span.Hours, span.Minutes);
        if (span.Hours > 0)
             return string.Format("{0} hours, {1} minutes", span.Hours, span.Minutes);
    
        return  string.Format("{0} minutes", span.Minutes);
    }
    
    0 讨论(0)
  • 2021-01-01 15:48

    With C# 7:

    string FormatTimeSpan(TimeSpan timeSpan)
    {
        string FormatPart(int quantity, string name) => quantity > 0 ? $"{quantity} {name}{(quantity > 1 ? "s" : "")}" : null;
        return string.Join(", ", new[] { FormatPart(timeSpan.Days, "day"), FormatPart(timeSpan.Hours, "hour"), FormatPart(timeSpan.Minutes, "minute") }.Where(x => x != null));
    }
    
    0 讨论(0)
提交回复
热议问题