The following line gives me a "String was not recognized by a valid DateTime" error:
DateTime.ParseExact("4/6/2016", "dd/MM/yyyy", Nothing)
I got this "working" example on stackoverflow, but it doesn't work for me: Parse Exact Sample and I can't figure out why.
EDIT (reedit, I mistakenly typed the last two attempts wrong): Still no good. This is what I've found after trying all the suggestions submitted so far (thanks all). Some more info, the date string is coming from a textbox control.
Dim xxx As String = "4/6/2016" 'OR = "04/06/2016" as necessary for the sample
This does not work:
DateTime.ParseExact(xxx, "M/d/yyyy", CultureInfo.InvariantCulture)
This does not work:
DateTime.ParseExact(xxx, "MM/dd/yyyy", CultureInfo.InvariantCulture)
After, I tried something simpler with just DateTime.Parse:
DateTime.ParseExact(xxx)
I typed this out by hand. I did NOT use values from a textbox control and it DID work:
DateTime.Parse("4/6/2016")
So frustrating
Your format says you'll have two digits for the day and the month. Your actual values only have one digit.
You have two options:
04/06/2016
d/M/yyyy
Additionally - and separately - you're passing in Nothing
as the format provider, which means the current culture will be used. Your format uses /
which is the culture-specific date separator. If your current culture doesn't use /
as its date separator, that's another problem. If you've got a fixed format, you probably want to specify CultureInfo.InvariantCulture
as the format specifier instead.
Here's a short but complete program demonstrating it working:
Option Strict On
Imports System
Imports System.Globalization
Public Class Test
Shared Sub Main()
Dim xxx As String = "4/6/2016"
Dim result as DateTime = DateTime.ParseExact(xxx, "M/d/yyyy", CultureInfo.InvariantCulture)
Console.WriteLine(result)
End Sub
End Class
See more on this question at Stackoverflow