时间跨度转换的用户输入时间的正确格式 VB

Proper format for user input of time for timespan conversion VB

我目前正在使用组合框让用户输入要存储到 DateTime 变量中的指定时间。然后将这些 DateTime 变量分别加上或减去以获得 TimeSpan 变量。 组合框文本的格式如下:

12:00:00 AM
01:00:00 AM
02:00:00 AM
03:00:00 AM
'ect...

这是将组合框信息输入 DateTime 变量时我的代码的样子:

parentsStart = CDate(ComboBox2.SelectedText)
parentsEnd = CDate(ComboBox3.SelectedText)

这显然不是工作代码。将用户输入到 DateTime 变量中的组合框或转换方法的正确格式是什么?还有没有更好的方法让用户通过 DateTimePicker 输入时间值?

我不认为时代的格式有什么问题。当您将 String 转换为 DateTime 对象时,您只需要使用 DateTime.Parse()

请原谅代码示例,因为我使用 https://dotnetfiddle.net 来模拟您的要求,所以我使用了 List 而不是 ComboBoxes。使用我的 List 对象的区域将替换为您的 ComboBox 对象

Imports System
Imports System.Collections.Generic

Public Module Module1

    Public Sub Main()
        Dim myComboBox As New List(Of String)
        myComboBox.Add("12:00:00 AM")
        myComboBox.Add("1:00:00 AM")
        myComboBox.Add("2:00:00 AM")
        myComboBox.Add("3:00:00 AM")

        Dim myComboBox2 As New List(Of String)
        myComboBox2.Add("12:00:00 AM")
        myComboBox2.Add("1:00:00 AM")
        myComboBox2.Add("2:00:00 AM")
        myComboBox2.Add("3:00:00 AM")

        ' myComboBox(2) selects 2:00:00 AM and converts it to a DateTime object
        Dim myTimeStart As DateTime = DateTime.Parse(myComboBox(2))
        ' myComboBox2(3) selecs 3:00:00 AM and converts it to a DateTime object
        Dim myTimeEnd As DateTime = DateTime.Parse(myComboBox2(3))
        ' Subtracting myTimeStart from myTimeEnd results in a TimeSpan object
        Dim myTimeSpan = myTimeEnd.Subtract(myTimeStart)

        ' Output to console to show the results of the subtraction
        Console.WriteLine(myTimeSpan)
    End Sub
End Module

结果:

01:00:00

点击https://dotnetfiddle.net/JOqFLB查看示例和结果

如果您想使用 DateTimePicker 而不是 ComboBox,请参阅 https://msdn.microsoft.com/en-us/library/vstudio/ms229631(v=vs.100).aspx。 DateTimePicker 可以设置为仅显示和配置时间。