2

我有以下方法来验证字符串是否是有效的日期时间:

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

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

现在,每当我尝试传递这样的字符串时,都会捕获异常“字符串未被识别为有效日期时间”:

“2013 年 12 月 31 日上午 12:00:00”

我不明白为什么会这样。有人可以帮我解决这个问题吗?

4

3 回答 3

4

尝试使用 DateTime 类中内置的 TryParse 方法,而不是 try/catch 块。它将您的字符串作为参数,如果转换成功,它将将该值放在“结果”变量中。它返回一个布尔值,表示它是否有效。

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

    return DateTime.TryParse(date, out result);
}
于 2013-06-29T12:42:23.760 回答
3

您当前的文化设置很可能与提供的格式日期不同。您可以尝试明确指定文化:

CultureInfo culture = new CultureInfo("en-US"); // or whatever culture you want
Convert.ToDateTime(date, culture);
于 2013-06-29T12:39:07.230 回答
1

You can also use DateTime.TryParseExact and pass a format string (eg. MM/dd/yy H:mm:ss zzz, see more here) to check if the date has a specific format.

于 2013-06-29T13:51:26.040 回答