Phil
Phil

Reputation: 1841

String / DateTime Conversion problem (asp.net vb)

I have this code:

Dim birthdaystring As String = MonthBirth.SelectedValue.ToString & "/" & DayBirth.SelectedValue.ToString & "/" & YearBirth.SelectedValue.ToString
Dim birthday As DateTime = Convert.ToDateTime(birthdaystring)

Which produces errors (String was not recognized as a valid DateTime.)

The string was "01/31/1963".

Any assistance would be appreciated.

Thanks.

Upvotes: 0

Views: 865

Answers (3)

Faruz
Faruz

Reputation: 9959

Try changing it to:

DateTime.Parse(birthdaystring);

I'm guessing it will work, but if not - you can add a second parameter to the parse saying the format you input, i.e.:

DateTime.Parse(birthdaystring,"MM/dd/yyyy");

Upvotes: 1

Guffa
Guffa

Reputation: 700342

The problem is probably that the culture used for parsing the date expects a MM/dd/yyyy format rather than dd/MM/yyyy format.

Instead of creating a string and parsing it, create the DateTime value directly:

Dim birthday As New DateTime(YearBirth.SelectedValue, MonthBirth.SelectedValue, DayBirth.SelectedValue)

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

Instead of creating a string which you later try to parse to a date try this:

Dim birthday As DateTime = new DateTime(_
    CType(YearBirth.SelectedValue, Integer), _
    CType(MonthBirth.SelectedValue, Integer), _
    CType(DayBirth.SelectedValue, Integer))

Upvotes: 1

Related Questions