DateTime.ParseExact returns today if date string and format are set to "General"

Shola Ogunde 0 Reputation points
2024-09-06T11:47:07.03+00:00

During troubleshooting, I came across this weird behaviour which occurs when parsing text to create a DateTime object in C# (in .Net Core 8.0).

Can anybody explain why the following statements return today's date when I would have expected them to fail?


if (DateTime.TryParseExact("General", "General", null, DateTimeStyles.None, out var dateTime))
    Debug.WriteLine(dateTime);

var dateTime2 = DateTime.ParseExact("General", "General", null);
Debug.WriteLine(dateTime2);

Is this behaviour expected? And if it is, can anyone explain why or how it makes sense?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,840 questions
C#
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.
10,910 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jiachen Li-MSFT 31,246 Reputation points Microsoft Vendor
    2024-09-06T12:52:55.25+00:00

    Hi @Shola Ogunde .

    This behavior is expected.

    According to the remark in DateTime.ParseExact Method.

    The DateTime.ParseExact(String, String, IFormatProvider) method parses the string representation of a date, which must be in the format defined by the format parameter. It also requires that the <Date> and <Time> elements of the string representation of a date and time appear in the order specified by format, and that s have no white space other than that permitted by format. If format defines a date with no time element and the parse operation succeeds, the resulting DateTime value has a time of midnight (00:00:00). If format defines a time with no date element and the parse operation succeeds, the resulting DateTime value has a date of DateTime.Now.Date.

    Because the format used for parsing is a string type parameter, not restricted to an enumeration type.

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 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.

    0 comments No comments

Your answer

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