简体   繁体   English

C# - 字符串未被识别为有效的日期时间

[英]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: 现在,只要我尝试传递这样的字符串,就会捕获异常“String未被识别为有效日期时间”:

"12/31/2013 12:00:00 AM" “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. 而不是try / catch块,尝试DateTime类中的内置TryParse方法。 It takes your string as a parameter and if it converts successfully it will place the value in the "result" variable. 它将您的字符串作为参数,如果它成功转换,它将把值放在“result”变量中。 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 ,请在此处查看更多内容)以检查日期是否具有特定格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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