Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timespan in milliseconds to minutes and seconds only

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?

like image 471
Gabbar Avatar asked Dec 07 '16 01:12

Gabbar


1 Answers

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}";
like image 56
Diego Avatar answered Nov 15 '22 16:11

Diego