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

时间:2012-06-13 22:27:52

标签: c# time formatting 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));
}

但我的问题是:有更好的方法吗?在我不需要帮助函数的地方可能更短。

2 个答案:

答案 0 :(得分:23)

使用Custom TimeSpan Format Strings

更短一些
private string FormatTimeSpan(TimeSpan time)
{
    return ((time < TimeSpan.Zero) ? "-" : "") + time.ToString(@"mm\:ss");
}

答案 1 :(得分:2)

以下.Net 4.0

您可以使用:

get { return Time.ToString().Substring(3); }