Davis
Davis

Reputation: 127

VB.NET variable date and time

I need help to save date and time into 1 variable to save in SQL params.

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

And i want to save into 1 variable with format "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"))

Upvotes: 2

Views: 5725

Answers (1)

Zay Lau
Zay Lau

Reputation: 1864

Although I am not quite understand how does those text boxes and the k works, I recommend you could use a new DateTime(year, month, day, hour, minute, second) to create a DateTime variable.

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")

Upvotes: 2

Related Questions