日期格式验证

时间:2013-08-05 07:12:31

标签: c#

如何确保只接受在控制台中输入的日期格式并将其存储在文本文件中,并且任何其他格式不应存储在文本文件中,并且应显示错误消息,提示用户输入日期格式正确。

Date Format = MM/DD/YYYY

使用以下代码13/10/2013显示错误消息,但即使输入正确的格式(如12/12/2013),它也会显示相同的错误消息并不断重复,如果不验证正确的格式。 return会暂停应用程序。

if(!DateTime.TryParseExact(Date,"MM-dd-yyyy",new CultureInfo("en-US"),DateTimeStyles.None,out date))
{
    Console.WriteLine("Invalid date format!");
    while(!DateTime.TryParseExact(Date,"MM-dd-yyyy",new CultureInfo("en-US"),DateTimeStyles.None,out date))
    {
        Console.WriteLine("Invalid Date Entered, please format MM-dd-yyyy");
        Date = Console.ReadLine();
    }
}

不允许使用字符串构建器和其他概念。怎么办?


我接受用户的输入为字符串,稍后检查,如果格式正确,如果它符合指定的格式,则将其转换回字符串,然后只有在用户输入时才会存储在我的文本文件中正确的日期格式。


public override bool IsValid(string value)
{
    string format = "MM/dd/yyyy";
    DateTime dt;

    if (DateTime.TryParseExact((String)value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
    {
        return IsValid(dt);
    }
    else
    {
        return false;
    }
}

上面的代码可以修改并与我的代码融合以使其正常工作吗?

3 个答案:

答案 0 :(得分:1)

将格式更改为"MM/dd/yyyy"

如果您需要使用MM/dd/yyyy验证日期格式,则需要在TryParseExact方法中将其作为格式字符串提供,您可以MM-dd-yyyy。所以你需要提供像01-01-2013

这样的输入

答案 1 :(得分:1)

以下代码将起作用:

            Console.WriteLine("Enter the Date Scheduled For the Meeting:");
            string Date = Console.ReadLine();
            DateTime Test;
            if(DateTime.TryParseExact(Date, "MM/dd/yyyy", null, DateTimeStyles.None, out Test) == true)
            {
                    Console.WriteLine("Date is in the correct Format");
            }
            else
            {
                     Console.Write("Date Not OK");
                     return;
            }

答案 2 :(得分:0)

如果您的格式是MM / DD / YYYY,为什么要解析MM-DD-YYYY?

 while(!DateTime.TryParseExact(Date,"MM/dd/yyyy",CultureInfo.InvariantCulture,DateTimeStyles.None,out date))
相关问题