It is an intended behavior of the CheckDefaultDateTime method, which dates back to the very first commit of Microsoft's library itself (2014). This method is called by DateTime.TryParseExact/DateTime.ParseExact, explaining why it defaults to today's date in certain cases.
https://github.com/microsoft/referencesource/blob/51cf7850defa8a17d815b4700b67116e3fa283c2/mscorlib/system/globalization/datetimeparse.cs#L2517
// Check if the parsed string only contains hour/minute/second values.
bool bTimeOnly = (result.Year == -1 && result.Month == -1 && result.Day == -1);
//
// Check if any year/month/day is missing in the parsing string.
// If yes, get the default value from today's date.
//
if (!CheckDefaultDateTime(ref result, ref result.calendar, styles)) {
TPTraceExit("0090 (failed to fill in missing year/month/day defaults)", dps);
return false;
}
In particular the line:
https://github.com/microsoft/referencesource/blob/master/mscorlib/system/globalization/datetimeparse.cs#L3381
if ((result.Year == -1) || (result.Month == -1) || (result.Day == -1)) {
/*
The following table describes the behaviors of getting the default value
when a certain year/month/day values are missing.
An "X" means that the value exists. And "--" means that value is missing.
Year Month Day => ResultYear ResultMonth ResultDay Note
X X X Parsed year Parsed month Parsed day
X X -- Parsed Year Parsed month First day If we have year and month, assume the first day of that month.
X -- X Parsed year First month Parsed day If the month is missing, assume first month of that year.
X -- -- Parsed year First month First day If we have only the year, assume the first day of that year.
-- X X CurrentYear Parsed month Parsed day If the year is missing, assume the current year.
-- X -- CurrentYear Parsed month First day If we have only a month value, assume the current year and current day.
-- -- X CurrentYear First month Parsed day If we have only a day value, assume current year and first month.
-- -- -- CurrentYear Current month Current day So this means that if the date string only contains time, you will get current date.
*/
The method also considers the DateTimeStyles.NoCurrentDateDefault flag, which influences whether the current date is used as a default when no date is provided.
s
andformat
will be accepted and return current date, tryDateTime.ParseExact("123", "123", null)
. – Synopsis"General"
is not a standard formatting string. "A standard date and time format string uses a single character as the format specifier to define the text representation of a DateTime or a DateTimeOffset value. Any date and time format string that contains more than one character, including white space, is interpreted as a custom date and time format string." (from your own link) – Tericaterina