Alex Alex - 1 month ago 11
Vb.net Question

VB.NET Date/Time formatting issues with Linq to SQL

I'm pulling in datetime information from SQL, converting it to a string then using substring to chop it in date, hour, and minute variables. In the database, the date is shown as MM/dd/YYYY, and the month/day always use two digits (such as 09/04/2016) but after the query it shows up in my application as (9/4/2016) which throws off my substring count. How do I get my query to keep the 0 in front when necessary?

Private Sub pullDate()
pulledDate = dgvTimeManager.SelectedItem.TimeIn.ToString
pulledDate = pulledDate.Substring(0, 10)

datepickerEdit.SelectedDate = Date.Parse(pulledDate)
End Sub

Private Sub pullStartTime()
pulledStartTime = dgvTimeManager.SelectedItem.TimeIn.ToString

If pulledStartTime.Length = 22 Then
pulledStartHour = pulledStartTime.Substring(11, 2)
pulledStartMinute = pulledStartTime.SubString(14, 2)
pulledStartAMPM = pulledStartTime.SubString(20, 2)
ElseIf pulledStartTime.Length = 21 Then
pulledStartHour = pulledStartTime.SubString(11, 1)
pulledStartMinute = pulledStartTime.SubString(13, 2)
pulledStartAMPM = pulledStartTime.SubString(19, 2)
End If

If pulledStartAMPM = "AM" Then
comboStartEditAMPM.SelectedIndex = 0
ElseIf pulledStartAMPM = "PM" Then
comboStartEditAMPM.SelectedIndex = 1
End If

txtStartHrEdit.Text = pulledStartHour
txtStartMinEdit.Text = pulledStartMinute
End Sub


dgvtimemanger is the datagrid that's displaying my time table, the starttime.length conditions are to take into account the hour being displayed as one digit or two (the same thing i'm dealing with now for the date)

Answer

You're spending way too much effort working with strings. Use the DateTime value you're given, and this code gets much simpler:

Private Sub pullDate()
    datepickerEdit.SelectedDate = dgvTimeManager.SelectedItem.TimeIn.Date
End Sub

Private Sub pullStartTime()
    Dim pulledStartTime As DateTime = dgvTimeManager.SelectedItem.TimeIn
    txtStartHrEdit.Text = pulledStartTime.ToString("hh")
    txtStartMinEdit.Text = pulledStartTime.ToString("mm")
    comboStartEditAMPM.SelectedIndex = If(pulledStartTime.Hour >= 12, 1, 0)         
End Sub

Additionally, I'd tend to write these kind of methods to accept an argument:

Private Sub SetStartTime(DateTime timeToSet)
    datepickerEdit.SelectedDate = timeToSet.Date
    txtStartHrEdit.Text = timeToSet.ToString("hh")
    txtStartMinEdit.Text = timeToSet.ToString("mm")      
    comboStartEditAMPM.SelectedIndex = If(timeToSet.Hour >= 12, 1, 0)   
End Sub

And then call them like this:

SetStartTime(dgvTimeManager.SelectedItem.TimeIn)

Note how the first one is so simple it's not even worth building the method anymore, and so I instead include the code as part of setting the time.