Gabbar
Gabbar

Reputation: 4066

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?

Upvotes: 12

Views: 19524

Answers (4)

ihor.eth
ihor.eth

Reputation: 2420

I do it this way

timespan.ToString("mm\\:ss");

Upvotes: 7

Diego
Diego

Reputation: 18379

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}";

Upvotes: 26

Reed Copsey
Reed Copsey

Reputation: 564791

You can format this yourself using the standard numeric format strings:

string output = string.Format("{0}:{1}", (int)timespan.TotalMinutes, timespan.Seconds);

Upvotes: 5

user744621
user744621

Reputation: 147

That is a pretty basic math problem.

Divide by 1000 to get total number of seconds.

Divide by 60 to get number of minutes. Total seconds - (minutes * 60) = remaining seconds.

Upvotes: 1

Related Questions