VB.NET变量的日期和时间

时间:2016-09-28 02:18:28

标签: vb.net datetime variables

我需要帮助将日期和时间保存到1个变量中以保存在SQL参数中。

I have textbox (txBulan) = "1",
textbox (txTahun) = "2016",
double (k) = "2",
string (time) = "13:00:00"

我想保存为1个格式为"MM/dd/yyyy HH:mm:ss"的变量。

dim CI as datetime

CI = CDate(Format((txBulan.Text & "/" & k-1 & "/" & CDbl(txTahun.Text) & " " & time), "MM/dd/yyyy HH:mm:ss"))

1 个答案:

答案 0 :(得分:1)

虽然我不太明白这些文本框和k是如何工作的,但我建议您使用new DateTime(year, month, day, hour, minute, second)来创建DateTime变量。

Dim txYear as TextBox ' Assume Text = 2016
Dim txMonth as TextBox ' Assume Text = 1
Dim txDay as TextBox ' Assume Text = 2
Dim time as String = "13:00:00"
Dim Hour as Integer = -1
Dim Minute as Integer = -1
Dim Second as Integer = -1

For Each piece as String in time.Split(":")
    ' For safety, add try-catch
    If (Hour < 0) Then
        Hour = Integer.Parse(piece)
    Else If (Minute < 0) Then
        Minute = Integer.Parse(piece)
    Else
        Second = Integer.Parse(piece)
    End If
End For

' For safety, cast .Text to integer value
Dim Ci AS New DateTime(
    Integer.Parse(txYear.Text),
    Integer.Parse(txMonth.Text),
    Integer.Parse(tx.Day.Text),
    Hour, Minute, Second
)
Dim DateString as String = Ci.ToString("MM/dd/yyyy HH:mm:ss")