Format TimeSpan to mm:ss for positive and negative TimeSpans
Asked Answered
R

2

12

I'm looking for a solution in .net 3.5 I wrote the following working solution:

private string FormatTimeSpan(TimeSpan time)
{
    return String.Format("{0}{1:00}:{2:00}", time < TimeSpan.Zero ? "-" : "", Math.Abs(time.Minutes), Math.Abs(time.Seconds));
}

But my Question is: Is there a better way? Maybe something shorter where I do not need an helper function.

Rigatoni answered 13/6, 2012 at 22:27 Comment(0)
T
31

Somewhat shorter, using Custom TimeSpan Format Strings:

private string FormatTimeSpan(TimeSpan time)
{
    return ((time < TimeSpan.Zero) ? "-" : "") + time.ToString(@"mm\:ss");
}
Tyrant answered 13/6, 2012 at 22:40 Comment(5)
Shouldn't the negative sign appear automatically from the time.ToString() ?Vineyard
@Vineyard - It doesn't, not with a custom format string. And there is no custom format specifier for it.Tyrant
I'm nur sure but does time.ToString(@"mm\:ss") work for .net 3.5?Rigatoni
Just got the idea to implement it as Extension that will make the functionality available all over my program.Rigatoni
@Tarion: @"mm\:ss" doesn't work for me either. Returns always "00:00". Someone a clue?Ululant
R
2

for below .Net 4.0

You can use:

get { return Time.ToString().Substring(3); }
Rf answered 30/1, 2014 at 17:35 Comment(2)
I think this is a smart hack.Widener
I'd recommend against this approach, as it relies on the default ToSring behavior, which is Culture dependent.Honky

© 2022 - 2024 — McMap. All rights reserved.