Xi Wang Xi Wang - 6 months ago 52
Vb.net Question

VB.NET How to get total hours and minutes in Listbox

Please help! I need to get the total hours and minutes which format is "HH:mm" from ListBox, for example:

11:20
22:40
34:00


Total: 68:00

I tried to use Datetime and TimeSpan, but it has error "The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar."

Here is my code:

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

Answer

Maybe this can help instead:

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 

You would still be casting Strings-Integers though, so I would put that inside a Try/Catch