2014-06-20 28 views
0

我的網絡系統中檢索從服務器DateTime類型的時間價值,我需要在標籤文本的特定格式來顯示它提取和格式化時間

The time value in DateTime type retrieved from server: 00:05:23.4994656 
Display it to be : 05:23 

If the time value has more than 1 hour 
Time value in DateTime type: 01:05:23.4994656 
Display it to be : 01:05:23 

我怎樣才能實現它的C#?

+1

你嘗試過這麼遠嗎?嘗試搜索「.NET格式化時間」(MSDN:[.NET框架中的格式化類型](http://msdn.microsoft.com/zh-cn/library/26etazsy.aspx))。 – Styxxy

+0

如果它們是'DateTime'或'TimeSpan',您仍可以格式化它們以使用'.ToString'方法顯示。 –

回答

0

您可以使用時間跨度分析它,並檢查它是否more than one Hour,然後格式化:

TimeSpan span = TimeSpan.Parse("00:05:23.4994656"); 
string displayStr = ""; 
if (span.Hours == 0) 
    displayStr = span.ToString(@"mm\:ss"); 
else 
    displayStr = span.ToString(@"hh\:mm\:ss"); 
+0

它顯示沒有超載的方法'ToString'takes 1個參數 – DEN

+0

什麼是你的應用程序的類型。我的示例在Windows窗體或控制檯應用程序中。類型TimeSpan在System namespace下。 –

+0

這是asp.net :) – DEN

0
string theTime; 
if (int.Parse(DateTime.Now.ToString("HH")) != 0) 
{ 
    theTime = DateTime.Now.ToString("HH:mm:ss"); 
} 
else 
{ 
    theTime = DateTime.Now.ToString("mm:ss"); 
}