C# DateTime.TryParse() could parse invalid date

T.Zacks 3,996 Reputation points
2021-09-01T14:44:18.903+00:00
            bool status = false;
            DateTime val;
            if (DateTime.TryParse("7.16", out val) == true)
                status= true;
            else
                status= false;

please run the code and see DateTime.TryParse() can parse 7.16 where as 7.16 is not a valid date. is it any bug?

rather this code properly worked.

            bool status = false;
            DateTime d;
            if (DateTime.TryParseExact("13/15/2021", new string[] { "dd/MM/yyyy", "MM/dd/yyyy" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out d))
            {
                status = true;
            }
            else
            {
                status = false;
            }

            return status;

Thanks

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. Jack J Jun 25,316 Reputation points
    2021-09-02T06:45:23.06+00:00

    @T.Zacks , based on my research, this is not a bug.

    Please refer to the DateParse.cs Source Code.(3395 rows)

    128591-image.png

    When we only set the month and the day, year is the current year.

    If the year is missing, assume the current year. (You can see it in the link)


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. AgaveJoe 30,491 Reputation points
    2021-09-01T15:07:47.317+00:00

    please run the code and see DateTime.TryParse() can parse 7.16 where as 7.16 is not a valid date. is it any bug?

    No. 7.16 is a valid date format.

    DateTime val;  
    Console.WriteLine(DateTime.TryParse("7.16", out val));  
    Console.WriteLine(val);  
    

    Results

    True  
    7/16/2021 12:00:00 AM  
    

    If you expect a specific date format then continue to use TryParseExact() and/or add input validation so the user cannot submit "7.16".

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.