简体   繁体   中英

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?

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);

尝试DateTime.ParseExact,你也可以传递一个格式字符串。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM