0
votes

I am trying to convert string into date on vb, but for some reason I get the following error message.

System.FormatException: 'String was not recognized as a valid DateTime.'

I am getting the date from date control on winform

dim selectedDate as string = dateControl1.text
dim selectedDt as Date = Date.Parse(selectedDate)

but if I put the same value in code instead of getting from dateControl, is ok

dim selectedDate as string = "19/01/2021"
dim selectedDt as Date = Date.Parse(selectedDate)

so I try to see if there is any different between value from dateControl1 and when type in the code since dateControl1.text should returning the same string value so I try to do this

dim selectedDate as string = "19/01/2021"
if selectedDate = dateControl1.text then
  debug.print ("same")
else
  debug.print ("different")
end if

when I run it, debug print "same"

and if I do this

dim selectedDate as string = "19/01/2021"
if selectedDate = dateControl1.text then
  debug.print ("same")
else
  debug.print ("different")
end if

dim selectedDt as Date = Date.Parse(dateControl1.text)

I get the same error even though the debug say "same"

so I am really confuse, why date.parse show error when I am getting the value from dateControl1.text and it's exactly the same string

am I missing something?

Thank you for your help.

Regards

  • Haris -
2
What is the date/time format of the current CultureInfo? Try DateTime.TryParse(), providing the parsing format. What is a date control (a control provided by what platform)? Doesn't it provide a Value property that returns a Date object? - Jimi
You are likely on a system where the standard date format is "MM/dd/yyyy" and you are passing value that can only be interpreted as "dd/MM/yyyy". You would need to use ParseExact or TryParseExact and specify the exact format or else call Parse or TryParse and provide an IFormatProvider that provided the appropriate date format. As suggested though, if you're using WinForms and a DateTimePicker control then you should not be touching its Text property but, rather, using the Value property. - jmcilhinney

2 Answers

0
votes

You can try this way, it should work:

dim selectedDt as Date = DateTime.ParseExact(dateControl1.text, "dd/MM/yyyy", CultureInfo.InvariantCulture)

For a safer way, you have to double check your value of the textbox first. by a try

DateTime.ParseExact Method

0
votes

What control is the date control? If it's a DateTimePicker then you can just get the date using the .Value property without having to do any conversion.

dim selectedDt as Date = dateControl1.Value