2016-05-18 67 views
1

請幫忙!我需要的總小時和分鐘,其格式爲「HH:MM」從Control,例如:VB.NET如何在列表框中獲取總小時數和分鐘數

11:20 
    22:40 
    34:00 

總:68:00

我試圖用日期時間和時間跨度,但它有錯誤:

「字符串表示的日期時間在日曆 System.Globalization.GregorianCalendar中不受支持」。

這裏是我的代碼:

ListBox_monthtime.Items.Add("11:20") 
    ListBox_monthtime.Items.Add("22:40") 
    ListBox_monthtime.Items.Add("34:00") 

    'SUM TIMES IN LISTBOX 
    Dim MyDateTimeMonthly As DateTime 
    Dim MyTimeSpanMonthly As New TimeSpan 

    For Each S As String In ListBox_monthtime.Items 
     MyDateTimeMonthly = DateTime.ParseExact(S, "HH:mm", System.Globalization.CultureInfo.InvariantCulture) 
     MyTimeSpanMonthly = MyTimeSpanMonthly.Add(New TimeSpan(MyDateTimeMonthly.Day, MyDateTimeMonthly.Hour, MyDateTimeMonthly.Minute, 0)) 
    Next 

    monthtime_txt.Text = (MyTimeSpanMonthly.Days * 24 + MyTimeSpanMonthly.Hours) & ":" & MyTimeSpanMonthly.Minutes 
+1

'「34:00」'不會解析,因爲TimeSpan會將它描述爲'1:10:00'。您最好將它們保留爲TimeSpans,並以任何您需要的格式顯示結果,而不是轉換爲字符串 – Plutonix

+0

謝謝,但我需要HH:mm格式來獲得最終結果。 –

+0

@Plutonix我嘗試了以下方法:Dim ts As TimeSpan = TimeSpan.Parse(「34:00」)'Dim t As TimeSpan = TimeSpan.ParseExact(「34:00」,「HH:mm」,Globalization。 CultureInfo.InvariantCulture)'。這兩種方法都收到了一個'System.OverflowException'。 –

回答

1

也許這可以幫助來代替:

ListBox_monthtime.Items.Add("11:43") 
ListBox_monthtime.Items.Add("22:56") 
ListBox_monthtime.Items.Add("34:21") 

Dim totalHours As Integer 
Dim totalMinutes As Integer 
For Each S As String In ListBox_monthtime.Items 
    totalHours += S.Split(":")(0) 
    totalMinutes += S.Split(":")(1) 
Next 

Dim remainder = totalMinutes Mod 60 
totalHours += totalMinutes/60 

Dim totalTime = totalHours & ":" & remainder.ToString("D2") 
monthtime_txt.Text = totalTime 

你仍然會鑄造字符串,整數的,所以我願意把一個嘗試內/ Catch

+1

謝謝!有用。 –

0

您不能使用大於24的小時值從字符串中創建DateTime或Timespan。您將需要解析輸入喲自己並將其轉換爲有效的字符串,供TimeSpan.parse()使用。

Dim TotalTime As TimeSpan = TimeSpan.Zero 
For Each item As String In ListBox_monthtime.Items 
    TotalTime = TotalTime.Add(TimeSpan.Parse(FormatTimeString(item))) 
Next 
Me.monthtime_txt.Text = $"{CInt(TotalTime.TotalHours).ToString}:{TotalTime.Minutes}" 


Private Function FormatTimeString(TimeString As String) As String 
    Dim timeArr() As String = TimeString.Split(":") 
    If CInt(timeArr(0)) > 24I Then 
     Dim d As Int32 = CInt(timeArr(0)) \ 24I 
     FormatTimeString = $"{d}:{(CInt(timeArr(0)) - (24I * d)).ToString}:{timeArr(1)}:00" 
    Else 
     FormatTimeString = TimeString 
    End If 
End Function 
相關問題