时间跨度的formatString带有可选小时 [英] TimeSpan FormatString with optional hours

查看:163
本文介绍了时间跨度的formatString带有可选小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时间跨度, TS ,也大多分钟和秒,但有时小时。
我想 TS 返回一个格式化字符串,就会给下面的结果:

I have a timespan, ts, that has mostly minutes and seconds, but sometimes hours. I'd like ts to return a formatted string that'll give the following results:

3:30 (hours not displayed, showing only full minutes)
13:30 
1:13:30 (shows only full hours instead of 01:13:30)

到目前为止,我有:

So far I have:

string TimeSpanText = string.Format("{0:h\\:mm\\:ss}", MyTimeSpan);

但它没有给出上述结果。我怎样才能达到我想要的结果?

but it's not giving the above results. How can I achieve the results I want?

推荐答案

我不认为一个单一的格式字符串会给你你想要什么,但建立自己的输出是一个简单的任务:

I don't think a single format string will give you what you want, but building the output yourself is a simple task:

public string FormatTimeSpan(TimeSpan ts)
{
    var sb = new StringBuilder();

    if ((int) ts.TotalHours > 0)
    {
        sb.Append((int) ts.TotalHours);
        sb.Append(":");
    }

    sb.Append(ts.Minutes.ToString("m"));
    sb.Append(":");
    sb.Append(ts.Seconds.ToString("ss"));

    return sb.ToString();
}

编辑:更好的想法

您可以对上面有像这样的时间跨度类扩展方法的方法:

You could make the method above an extension method on the TimeSpan class like so:

public static class Extensions
{
    public static string ToMyFormat(this TimeSpan ts)
    {
        // Code as above.
    }
}

然后用这个是调用 ts.ToMyFormat()

这篇关于时间跨度的formatString带有可选小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆