Jamie Taylor
Jamie Taylor

Reputation: 3530

Convert string to date in ASP.Net

I'm trying to convert a string into a date format

My string looks like this

Dim MyString as String = "June 2011"

And I'm trying to convert it like this

Convert.ToDateTime(MyString).ToString("MM yyyy")

But it's giving me the error

Syntax error converting datetime from character string.

The desired output would be either 06/2011 or 01/06/2011. The value of my string will only ever have the month and year in though.

Any ideas?

Upvotes: 1

Views: 22577

Answers (4)

Christian Hayter
Christian Hayter

Reputation: 31071

A datetime object in .NET represents one single point in time. To create one from a Gregorian calendar date, you need all three parts (day, month, year), otherwise it can't represent one single point in time.

Since your business requirement is to assume that the day number is 1 if not provided, just insert that number into the string before parsing.

Dim myDate As Date = Convert.ToDateTime("1 " & MyString)

EDIT:

Sorry, forgot to mention that string manipulations like that are of course culture-dependent. You don't mention what culture you are in. "June 2011" can imply either en-GB or en-US. Since inserting the day number at the start of the string is easier than trying to insert it between the month and year, I suggest you go for something like this.

Dim myDate1 As Date = Date.Parse("1 " & myString, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.AllowWhiteSpaces)

Upvotes: 6

dbasnett
dbasnett

Reputation: 11773

This worked for me

    Dim provider As Globalization.CultureInfo = Globalization.CultureInfo.InvariantCulture
    Dim MyString As String

    Dim d As DateTime = DateTime.Now 'test start

    'test all Month Year strings
    For x As Integer = 1 To 12
        MyString = d.ToString("MMMM yyyy") 'convert date to March 2011 then April 2011 then...
        Dim dt As DateTime = DateTime.ParseExact(MyString, "MMMM yyyy", provider)
        Debug.WriteLine(MyString & "   " & dt.ToString)
        d = d.AddMonths(1)
    Next

Upvotes: 1

Cosmin
Cosmin

Reputation: 2385

DateTime.Parse(MyString).ToString("MM yyyy")

Upvotes: 1

Tim Rogers
Tim Rogers

Reputation: 21723

Convert.ToDateTime() only takes the full date so try prepending 01 as the day first i.e.

Convert.ToDateTime("01 " + MyString)

Upvotes: 2

Related Questions