2016-09-15 76 views
1

下面的代碼有效。最後一行將代碼格式化爲dd:hh:mm。我怎樣才能把它顯示爲hh:mm。如果我將最後一行更改爲Convert Timespan - Gridview

e.Row.Cells[4].Text = timeSpent.ToString(@"hh\:mm"); 

我在24小時內收到一個異常。其目的是讓輸出26:30,而不是1時02分30秒

我的代碼是:

TimeSpan timeSpent = TimeSpan.Zero; 

protected void GridViewFortNight_RowDataBound(object sender, GridViewRowEventArgs e) 
      { 
       var tempTimeCalc = ""; 

       if (e.Row.RowType == DataControlRowType.DataRow) 
       { 
        tempTimeCalc = e.Row.Cells[4].Text.ToString(); 

        timeSpent += TimeSpan.Parse(tempTimeCalc); 


       } 
       else if (e.Row.RowType == DataControlRowType.Footer) 
       { 

        e.Row.Cells[4].Text = timeSpent.ToString(@"dd\:hh\:mm"); 

       } 


      } 
+0

既然你想通過24小時,我會猜測你正在試圖積累自從和事件或類似事件以來已經過去的時間。你能告訴我你想要達到什麼嗎?你爲什麼需要超過24小時? – Agustin0987

回答

1

它不支持內置的格式字符串。你必須深入一點,並自己做一些格式化。這並不是說不好,但:

e.Row.Cells[4].Text = string.Format("{0:00}:{1:00}", (int)timeSpent.TotalHours, timeSpent.Minutes); 
+0

謝謝,這工作:)請你可以給出一個簡短的解釋使用的格式。謝謝 – user6741701

+0

這裏是String.Format文檔:https://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx這裏是自定義數字格式字符串文檔: https://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx –

0

你可以做

string s = 
     $"{((int)timeSpent.TotalHours).ToString("00")}:{timeSpent.Minutes.ToString("00")}" 
0

您可以添加dataformatstring = 「{0:M-DD-YYYY}」 屬性綁定字段,這樣

<asp:BoundField DataField="Date" HeaderText="Date" DataFormatString="{0:dd-M-yyyy}" />