TimeSpan “pretty time” format in C#

后端 未结 3 871
小蘑菇
小蘑菇 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: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));
    }
    

提交回复
热议问题