Why is this DateTime.ParseExact statement not working?

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

Jon Skeet
people
quotationmark

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:

  • Follow the format you've specified, e.g. 04/06/2016
  • Change the format to match the value, e.g. 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

people

See more on this question at Stackoverflow