I have a Timespan that is always in milliseconds, but I need to show the date in minutes and seconds only so that it's always "mm:ss"
. Even if there are hours in the timespan, the output string should contain only minutes and seconds.
For example, if there is a timespan of 02:40:30
, it should get converted to 160:30
.
Is there a way to achieve this?
Reed's answer is ALMOST correct, but not quite. For example, if timespan is 00:01:59, Reed's solution outputs "2:59" due to rounding by the F0
numeric format. Here's the correct implementation:
string output = string.Format("{0}:{1:00}",
(int)timespan.TotalMinutes, // <== Note the casting to int.
timespan.Seconds);
In C# 6, you can use string interpolation to reduce code:
var output = $"{(int)timespan.TotalMinutes}:{timespan.Seconds:00}";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With