Timespan in milliseconds to minutes and seconds only
Asked Answered
T

4

11

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?

Tortricid answered 7/12, 2016 at 1:13 Comment(4)
Is the input is Timespan type or string?Labyrinthine
Consider doing this by hand. Given a certain number of milliseconds, could you convert it into minutes and seconds using basic math?Spermine
Is this what you are looking for: https://mcmap.net/q/894966/-format-timespan-to-mm-ss-for-positive-and-negative-timespans?Stale
How the 30 seconds in the input becomes 20 in output?Labyrinthine
L
23

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}";
Logarithmic answered 7/12, 2016 at 1:23 Comment(4)
Thank you. I noticed the extra minute in my testing as well.Tortricid
@Logarithmic Note, that if timespan has non-zero milliseconds they will be discarded. So if your timespan is 1h 59s and 999ms it will be output as "1:59" and not as "2:00".Candlewick
what about timespan.ToString("mm\\:ss");Scapolite
Don't put that in a PR, you should use formattingDe
S
7

I do it this way

timespan.ToString("mm\\:ss");
Scapolite answered 5/3, 2020 at 21:44 Comment(1)
61 minutes will show up as "01:00" - whoops!Ocean
C
5

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

string output = string.Format("{0}:{1}", (int)timespan.TotalMinutes, timespan.Seconds);
Cocainism answered 7/12, 2016 at 1:15 Comment(1)
Diego is correct in that the TotalMinutes rounds it to the nearest minute which ended up being an extra minute.Tortricid
B
1

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.

Binding answered 7/12, 2016 at 1:16 Comment(1)
I know. I did that but I wanted to see if there was a more straightforward way.Tortricid

© 2022 - 2024 — McMap. All rights reserved.