简体   繁体   中英

C# - String was not recognized as valid datetime

I have the following method in order to verify whether a string is a valid datetime:

public bool isDate(string date)
        {
            bool check = false;

            try
            {
                DateTime converted_date = Convert.ToDateTime(date);
                check = true;
            }
            catch (Exception)
            {
                check = false;
            }
            return check;
        }

Now, the exception "String was not recognized as valid datetime" is caught whenever I try to pass a string like this:

"12/31/2013 12:00:00 AM"

I cannot understand why this is happening. Can someone help me solve this please?

Instead of the try/catch block, try the built in TryParse method in the DateTime class. It takes your string as a parameter and if it converts successfully it will place the value in the "result" variable. It returns a boolean value representing whether it worked or not.

public bool isDate(string date)
{
    var result = new DateTime();

    return DateTime.TryParse(date, out result);
}

Most likely your current culture settings are different from the format date is provided in. You can try specifying the culture explicitly:

CultureInfo culture = new CultureInfo("en-US"); // or whatever culture you want
Convert.ToDateTime(date, culture);

您还可以使用DateTime.TryParseExact并传递格式字符串(例如, MM/dd/yy H:mm:ss zzz ,请在此处查看更多内容)以检查日期是否具有特定格式。

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