1

我正在使用以下函数来确定输入字符串是否为有效日期。

public static bool IsDate(string date)
        {
            DateTime Temp;

            if (DateTime.TryParse(date, out Temp))
                return true;
            else
                return false;
        }

问题是当我输入“1997-09”时它返回true。我希望它检查完整的日期,如“1997-08-12”

而且没有固定日期格式。输入也可以是“2012 年 2 月 19 日”

4

8 回答 8

3

And no there is no fix date format. Input could also be "19-Feb-2012"

There must be, otherwise it's nonesense. If you haven't defined how your system must behave you'd better stop coding and take a moment to define it.

You could use the TryParseExact method which allows you to specify one or more formats you would like to handle.

于 2012-04-19T11:52:53.783 回答
2

You should establish list of a correct date formats and then check with DateTime.TryParseExact, something like this:

string format = "yyyy-MM-dd";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
    DateTimeStyles.None, out dateTime))
于 2012-04-19T11:55:34.857 回答
2

one easy condition you can add:

    public static bool IsDate(string date)
    {
        DateTime Temp;
        return(DateTime.TryParse(date, out Temp)&&date.Length>=10)
    }
于 2012-04-19T11:55:34.843 回答
1

Use DateTime.TryParse, you can specify the format then, more here. http://msdn.microsoft.com/en-us/library/9h21f14e.aspx

于 2012-04-19T11:52:21.147 回答
0

可以直接返回解析结果:

public static bool IsDate(string value)
{
    DateTime date;
    return DateTime.TryParse(value, out date);
}

它适用于您提供的格式(至少在当前文化“en-US”时)。

于 2012-04-19T11:50:54.103 回答
0

要解决此问题,您应该datetime-format在您的应用程序中定义 a。

在您访问的任何网页上,如果您看到一个编译表格,您可能也会看到一些日期字段,并且在它附近会出现类似以下内容:

DD-MM-YYYY, 或MM/DD/YY, 或其他东西。

Define for your application format, make it esplicit for the user and check on correctness according to your format.

Just an hypothetic example:

say user inserted a date and you store it into the string like DD-MM-YYYY, one of possible choice could be simply say :

if(dateTimeUserString.Split('-').Length < 3)
    //not valid string !

I repeat, this is just an example you should choose more appropriate way for your application.

于 2012-04-19T11:51:34.553 回答
0

DateTime.TryParse does have an overload that takes an IFormatProvider to allow specification of custom formats. You may need to define multiple IFormatPrividers to check the various strings you may expect as valid.

Also, rather than the if/else, you could also shorten your code a bit by

return DateTime.TryParse(date, out Temp);
于 2012-04-19T11:53:34.510 回答
0

Your code will run just fine and check the given date string if it can be a valid date using all of the current culture's date formats including this 19-Feb-2012 or 1997-09 of yours or even 19 february.

This makes you flexible in date input.

But if flexibility is not what your are looking for then try to parse for one or more specific formats using TryParseExact.

于 2012-04-19T12:17:26.517 回答