Search code examples
vb.netdatetimedatetime-formatunhandled-exceptionstring-to-datetime

Different date time format of the user causing an error


My application is giving an error on different installation based on their different date/time format which my codes are based on

for example below original code ;

Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DTPTarihSec.ValueChanged
    Dim BaslangicTarihi As Date
    Dim BitisTarihi As Date


    BaslangicTarihi = "16/04/1996" 'TCMB kayıtları en eski bu tarihe kadar
    BitisTarihi = Date.Today

    If hatasayac = False Then
        SecilenTarih = DTPTarihSec.Value
    End If

    hatasayac = False

    If (SecilenTarih > BitisTarihi) Then

        MsgBox("İleri tarihli kur bilgileri bulunmamaktadır. Lütfen uygun bir tarih giriniz. " & vbCrLf & vbCrLf &
               "Kurların geçerli olduğu en son tarihe yönlendirildiniz !", vbOKOnly + vbInformation, "TCMB Döviz Kurları")
        hatasayac = True
        If Now.DayOfWeek.ToString = "Cumartesi" Or Now.DayOfWeek.ToString = "Saturday" Then
            SecilenTarih = Date.Today.AddDays(-1)
            DTPTarihSec.Value = Date.Today.AddDays(-1)

        ElseIf Now.DayOfWeek.ToString = "Pazar" Or Now.DayOfWeek.ToString = "Sunday" Then
            SecilenTarih = Date.Today.AddDays(-2)
            DTPTarihSec.Value = Date.Today.AddDays(-2)

        Else
            SecilenTarih = Date.Today
            DTPTarihSec.Value = Date.Today

        End If


    End If

is giving following error on one of the user computer ;

Unhandled exception has occurred in your application... If you click Quit, the application will close immediately. Conversation from string "16/04/1996" by type 'Date' is not valid.

This is because of the following code line ;

 BaslangicTarihi = "16/04/1996" 'TCMB kayıtları en eski bu tarihe kadar
BitisTarihi = Date.Today

If hatasayac = False Then
    SecilenTarih = DTPTarihSec.Value
End If 

but it is not giving error on my computer.

My question is about ;How to handle this error which will prevent all different date and time format on different computer


Solution

  • Don't use string to populate a date variable, use a date.

    Dim BaslangicTarihi = New Datetime(1996, 04, 16)
    

    I would suggest you turn Option Strict On.

    Also, you should properly use the enum for DayOfWeek instead of the string.

    If Now.DayOfWeek = Day​OfWeek.Saturday Then