What is the recommended way of formatting TimeSpan objects into a string with a custom format?
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.