适当的格式,用于用户输入时间板转换VB的时间



我当前正在使用组合框供用户输入指定的时间,以存储在dateTime变量中。然后,将分别添加或减去这些日期变量,以获取时间pan变量。组合框文本如果是这样的格式:

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查看样本和结果

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

最新更新