VB.NET如何在列表框中获取总小时和分钟数
请帮忙!我需要从列表框中获取格式为“HH:mm”的总小时和分钟数,例如:VB.NET如何在列表框中获取总小时和分钟数,vb.net,datetime,listbox,timespan,Vb.net,Datetime,Listbox,Timespan,请帮忙!我需要从列表框中获取格式为“HH:mm”的总小时和分钟数,例如: 11:20 22:40 34:00 总数:68:00 我尝试使用Datetime和TimeSpan,但出现错误: “日历中不支持由字符串表示的日期时间 系统、全球化、格雷戈里安卡伦达。” 这是我的密码: ListBox_monthtime.Items.Add("11:20") ListBox_monthtime.Items.Add("22:40") ListBox_mont
11:20
22:40
34:00
总数:68:00
我尝试使用Datetime和TimeSpan,但出现错误:
“日历中不支持由字符串表示的日期时间
系统、全球化、格雷戈里安卡伦达。”
这是我的密码:
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
也许这会有所帮助:
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
尽管如此,您仍然可以将字符串转换为整数,因此我将把它放在Try/Catch中,您不能使用大于24的小时值从字符串创建DateTime或Timespan。您需要自己解析输入,并将其转换为有效字符串,以供
TimeSpan.parse()
使用
“34:00”
不会解析,因为TimeSpan会将其描述为1:10:00
。您最好将其保留为TimeSpan,只以您需要的任何格式显示结果,而不是转换为StringThank,但我需要HH:mm格式作为最终结果。@Protoix我尝试了以下方法:Dim ts as TimeSpan=TimeSpan.Parse(“34:00”)
和Dim ts as TimeSpan=TimeSpan.ParseExact(“34:00”,“HH:mm”,Globalization.CultureInfo.InvariantCulture)
。我收到了两种方法的System.OverflowException
。我想你错过了以任何需要的格式显示它们的部分。@ᴎᴅᴏƞвєнᴎєƞ当然有。如果你想最终计算时间跨度,代码应该使用时间跨度而不是字符串。@我想你可能错过了需要获取总小时和分钟的部分,这是以特定格式列出的时间的总和,格式是“HH:mm”,而不是将现有时间跨度的值格式化为特定格式。为了将timespan添加到另一个timespan,首先需要一个timespan。
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