简体   繁体   中英

How to check the entered date with tryparse

I need to check the entered date with tryparse and, if entered correctly, return the date and add it to the student list as the student's date of birth. But no matter what date I check, I am informed that I entered it incorrectly. I would be glad if you could help me solve this problem.

    static public DateTime TarihAl(string mesaj)   
    {
            DateTime d;

            do
            {
                try
                {
                    Console.Write(mesaj);
                    string s = Console.ReadLine();

                    if (DateTime.TryParse(s, out d))

                    {
                        throw new Exception("Giriş tanımlanamadı. Tekrar deneyin.");
                    }

                    else
                    {
                        return s;
                       
                    }

                }
                catch (Exception e)
                {

                    Console.WriteLine(e.Message);
                }

            } while (true);

        }

Your code basically says "if TryParse is successful, throw a new Exception: 'Giriş tanımlanamadı. Tekrar deneyin.'" If you instead replaced that exception with something like Console.WriteLine(d); , you would see the parsed DateTime d that you entered as a string ( s ). Your throw new Exception() code likely belongs in the "else" portion of that code block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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