Coding Duchess
Coding Duchess

Reputation: 6899

Cannot convert date string to DateTime

I have a string:

string test="September 9th, 2015"

I need to convert it to DateTime format so I tried:

DateTime dt= Convert.ToDateTime(test);

and got an exception (String was not recognized as a valid DateTime). I am thinking it might be due to "th" after the day. Is there an easy way to convert this string to DateTime?

Upvotes: 2

Views: 1736

Answers (3)

user5166622
user5166622

Reputation:

Use this since you are parsing a string not converting it.

DateTime dt = DateTime.ParseExact(test, "MMMM d\"th\", yyyy")

More information can be found here https://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx

Upvotes: 0

arunlalam
arunlalam

Reputation: 1838

Try this function

private static DateTime ParseDate(string date)
{
   string[] formats =
        {
            "MMMM d\"st\", yyyy",
            "MMMM d\"nd\", yyyy",
            "MMMM d\"rd\", yyyy",
            "MMMM d\"th\", yyyy"
        };
    DateTime dt;
    if (DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
    {
            return dt;
    }

    throw new InvalidOperationException("Invalid Input");

}

Call using

DateTime dt= ParseDate(test);

Upvotes: 6

Niklas Raab
Niklas Raab

Reputation: 31

Try DateTime.ParseExact there you can pass an format string also.

Upvotes: 2

Related Questions