How can I String.Format a TimeSpan object with a custom format in .NET?

后端 未结 19 1244
情深已故
情深已故 2020-11-22 12:25

What is the recommended way of formatting TimeSpan objects into a string with a custom format?

19条回答
  •  清酒与你
    2020-11-22 12:52

    This is the approach I used my self with conditional formatting. and I post it here because I think this is clean way.

    $"{time.Days:#0:;;\\}{time.Hours:#0:;;\\}{time.Minutes:00:}{time.Seconds:00}"
    

    example of outputs:

    00:00 (minimum)

    1:43:04 (when we have hours)

    15:03:01 (when hours are more than 1 digit)

    2:4:22:04 (when we have days.)

    The formatting is easy. time.Days:#0:;;\\ the format before ;; is for when value is positive. negative values are ignored. and for zero values we have;;\\ in order to hide it in formatted string. note that the escaped backslash is necessary otherwise it will not format correctly.

提交回复
热议问题