display timespan nicely

空扰寡人 提交于 2019-12-04 02:10:52

Something like:

public static string PrintTimeSpan(int secs)
{
   TimeSpan t = TimeSpan.FromSeconds(secs);
   string answer;
   if (t.TotalMinutes < 1.0)
   {
     answer = String.Format("{0}s", t.Seconds);
   }
   else if (t.TotalHours < 1.0)
   {
     answer = String.Format("{0}m:{1:D2}s", t.Minutes, t.Seconds);
   }
   else // more than 1 hour
   {
     answer = String.Format("{0}h:{1:D2}m:{2:D2}s", (int)t.TotalHours, t.Minutes, t.Seconds);
   }

   return answer;
}
kaj

I think you can simplify this by removing the "D2" aspect of the format and then you won't need a special case for the under ten minutes option. Basically just using

string.Format("{0}m:{1}s", t.Minutes, t.Seconds);

will get you one or two digits as required. So your final case is:

string.Format("{0}h:{1}m:{2}s", t.Hours, t.Minutes, t.Seconds);
Kristof

According to msdn try this:

if (secs < 60)
{
    answer = t.Format("s");
}
else if (secs < 600)//tenmins
{
    answer = t.Format("m:s");
}
// ...
readonly static Char[] _colon_zero = { ':', '0' };
// ...

var ts = new TimeSpan(DateTime.Now.Ticks);
String s = ts.ToString("h\\:mm\\:ss\\.ffff").TrimStart(_colon_zero);
.0321
6.0159
19.4833
8:22.0010
1:04:2394
19:54:03.4883
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!