将TimeSpan格式化为mm:ss表示正负TimeSpans

Tar*_*ion 9 c# formatting time string-formatting

我正在寻找.net 3.5的解决方案我写了以下工作解决方案:

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

但我的问题是:有更好的方法吗?也许更短的地方,我不需要辅助功能.

Ode*_*ded 23

使用Custom TimeSpan Format Strings更短一点:

private string FormatTimeSpan(TimeSpan time)
{
    return ((time < TimeSpan.Zero) ? "-" : "") + time.ToString(@"mm\:ss");
}
Run Code Online (Sandbox Code Playgroud)

  • @Tisho - 它没有,不是自定义格式字符串.并且没有自定义格式说明符. (4认同)