Format TimeSpan to mm:ss for positive and negative TimeSpans

。_饼干妹妹 提交于 2019-12-09 15:45:26

问题


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.


回答1:


Somewhat shorter, using Custom TimeSpan Format Strings:

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



回答2:


for below .Net 4.0

You can use:

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


来源:https://stackoverflow.com/questions/11024228/format-timespan-to-mmss-for-positive-and-negative-timespans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!