Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format TimeSpan to mm:ss for positive and negative TimeSpans

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.

like image 431
Tarion Avatar asked Jun 13 '12 22:06

Tarion


2 Answers

Somewhat shorter, using Custom TimeSpan Format Strings:

private string FormatTimeSpan(TimeSpan time)
{
    return ((time < TimeSpan.Zero) ? "-" : "") + time.ToString(@"mm\:ss");
}
like image 54
Oded Avatar answered Nov 14 '22 02:11

Oded


for below .Net 4.0

You can use:

get { return Time.ToString().Substring(3); }
like image 24
matthy Avatar answered Nov 14 '22 04:11

matthy