【发布时间】:2016-05-18 21:31:41
【问题描述】:
请帮忙!我需要从 ListBox 中获取格式为“HH:mm”的总小时数和分钟数,例如:
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
【问题讨论】:
-
"34:00"不会解析,因为 TimeSpan 会将其描述为1:10:00。您最好将它们保留为 TimeSpan 并以您需要的任何格式显示结果,而不是转换为字符串 -
谢谢,但我需要 HH:mm 格式的最终结果。
-
@Plutonix 我尝试了以下方法:
Dim ts As TimeSpan = TimeSpan.Parse("34:00")和Dim ts As TimeSpan = TimeSpan.ParseExact("34:00", "HH:mm", Globalization.CultureInfo.InvariantCulture)。两种方法我都收到了System.OverflowException。 -
我猜你错过了关于以你需要的任何格式显示它们的部分。 @вʀaᴎᴅᴏƞвєнᴎєƞ 当然可以。如果你想最终对时间跨度求和,代码应该使用时间跨度而不是字符串。
-
@Plutonix 我想你可能错过了关于需要得到总小时和分钟的部分,这是以特定格式列出的时间的总和格式为“HH:mm”,而不是将现有时间跨度的值格式化为特定格式。为了将时间跨度添加到另一个时间跨度,您需要一个时间跨度开始。
标签: vb.net datetime listbox timespan