Nim*_*oud 7 c# formatting timespan
我需要显示经过时间跨度的最简单版本.有没有准备好的事情呢?
样品:
HH:mm:ss
10:43:27 > 10h43m27s
00:04:12 > 4m12s
00:00:07 > 7s
Run Code Online (Sandbox Code Playgroud)
我想我需要一个格式提供程序来消磨时间.
Kel*_*sey 10
简单的扩展方法应该足够了:
static class Extensions
{
public static string ToShortForm(this TimeSpan t)
{
string shortForm = "";
if (t.Hours > 0)
{
shortForm += string.Format("{0}h", t.Hours.ToString());
}
if (t.Minutes > 0)
{
shortForm += string.Format("{0}m", t.Minutes.ToString());
}
if (t.Seconds > 0)
{
shortForm += string.Format("{0}s", t.Seconds.ToString());
}
return shortForm;
}
}
Run Code Online (Sandbox Code Playgroud)
用以下方法测试:
TimeSpan tsTest = new TimeSpan(10, 43, 27);
string output = tsTest.ToShortForm();
tsTest = new TimeSpan(0, 4, 12);
output = tsTest.ToShortForm();
tsTest = new TimeSpan(0, 0, 7);
output = tsTest.ToShortForm();
Run Code Online (Sandbox Code Playgroud)
Ste*_*rov 10
这是一个单行(几乎),假设你有TimeSpanobjectL
(new TimeSpan(0, 0, 30, 21, 3))
.ToString(@"d\d\ hh\hmm\mss\s")
.TrimStart(' ','d','h','m','s','0');
Run Code Online (Sandbox Code Playgroud)
示例代码输出
30m21s
Run Code Online (Sandbox Code Playgroud)
第一行只是TimeSpan为了示例而创建一个对象,以.ToString您要求的格式对其进行格式化,然后.TrimStart删除您不需要的前导字符.