【问题标题】:Visual Basic date format validator not working?Visual Basic 日期格式验证器不起作用?
【发布时间】:2019-11-06 16:08:07
【问题描述】:

我正在尝试创建一个程序来验证格式为 DDMMYYYY 的输入日期的格式。我尝试使用while 循环的集合来执行此操作,但它似乎不起作用,我不知道为什么!

这是我的代码:

Console.WriteLine("Enter your date of birth (DDMMYYYY): ")
            Dim dob As String = Console.ReadLine
            While CInt(Mid(dob, 3, 2)) > 12 Or CInt(Mid(dob, 3, 2)) < 1
                Console.WriteLine("x-----x")
                Console.WriteLine("Format Incorrect!")
                Console.WriteLine("Enter your date of birth: ")
                dob = Console.ReadLine
            End While
            While CInt(Mid(dob, 3, 2)) = 4 Or 6 Or 9 Or 1 And CInt(Mid(dob, 1, 2)) > 30
                Console.WriteLine("x-----x")
                Console.WriteLine("Format Incorrect!")
                Console.WriteLine("Enter your date of birth: ")
                dob = Console.ReadLine
            End While
            While CInt(Mid(dob, 3, 2)) = 2 And CInt(Mid(dob, 1, 2)) > 29
                Console.WriteLine("x-----x")
                Console.WriteLine("Format Incorrect!")
                Console.WriteLine("Enter your date of birth: ")
                dob = Console.ReadLine
            End While
            While CInt(Mid(dob, 1, 2)) < 1
                Console.WriteLine("x-----x")
                Console.WriteLine("Format Incorrect!")
                Console.WriteLine("Enter your date of birth: ")
            End While
            Console.WriteLine("Thank You!")

我研究了其他方法,但没有找到任何适合我正在寻找的解决方案。

【问题讨论】:

    标签: vb.net date validation format


    【解决方案1】:

    在你的第二个 while 循环中,你写了:

    CInt(Mid(dob, 3, 2)) = 4 Or 6 Or 9 Or 1

    这种语法是不正确的,因为在每个布尔运算符(Or/And 等)之间应该有一个可以评估为真或假的语句 - 而不仅仅是一个数字。试试这个:

    Dim month As Integer = CInt(Mid(dob, 3, 2))
    While (month = 4 Or month = 6 Or month = 9 Or month = 11) And CInt(Mid(dob, 1, 2)) > 30
    

    希望你能从中明白我的意思。请注意,我还在所有 Or 运算符周围加上括号,以便将其解释为 (a or b or c or d) 和 e 而不是 (a or b or c) 或 (d 和 e).

    【讨论】:

    • @Mary 你可以使用 SubString,但我想保持答案简洁并解释实际问题,而不是给出完美的解决方案。
    【解决方案2】:

    您可以使用DateTime.TryParseExact()。一个例子:

    Sub Main()
        Console.WriteLine("Enter your date of birth (DDMMYYYY): ")
        Dim d As Date
        Do
            Dim dob = Console.ReadLine
            If DateTime.TryParseExact(dob, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, d) Then
                Exit Do
            End If
            Console.WriteLine("Please try again, pay particular attention to the format, no spaces or other characters.")
        Loop
        'you now have a real date called d
        Debug.Print(d.ToString("MM/dd/yyyy"))
        Console.WriteLine("Thank You!")
        Console.ReadLine()
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2012-08-11
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多