请帮忙!我需要得到总时数和分钟数,格式为" HH:mm"来自ListBox,例如:
11:20
22:40
34:00
总计:68:00
我尝试使用Datetime和TimeSpan,但它有错误:
"日历中不支持字符串表示的DateTime 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
答案 0 :(得分:2)
也许这会有所帮助:
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
你仍然会施放Strings-Integers,所以我会把它放在Try / Catch中
答案 1 :(得分:0)
您不能使用小于24的小时值从字符串创建DateTime或Timespan。您需要自己解析输入并将其转换为TimeSpan.parse()
使用的有效字符串。< / p>
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