-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
Description
There is a bug in the handling of the DateTime custom format handler for the "F" (optional fractional seconds) format specifier. It only occurs when a single "F" is specified.
Reproduction Steps
using System.Globalization;
var dateTime = new DateTime(2025, 1, 2, 3, 4, 5);
var c = CultureInfo.InvariantCulture;
var f = "yyyy-MM-ddTHH:mm:ss.F";
var s = dateTime.ToString(f, c);//"2025-01-02T03:04:05"
// throws FormatException: 'String '2025-01-02T03:04:05' was not recognized as a valid DateTime.'
var r = DateTime.ParseExact(s, f, c, DateTimeStyles.None); Expected behavior
In the minimal repro, the ParseExact should "roundtrip" the input value.
Actual behavior
It throws a FormatException with the message 'String '2025-01-02T03:04:05' was not recognized as a valid DateTime.'
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
The bug appears to be in this block of code:
runtime/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeParse.cs
Lines 4458 to 4471 in 252034f
| if (!str.Match(ch)) | |
| { | |
| if (format.GetNext()) | |
| { | |
| // If we encounter the pattern ".F", and the dot is not present, it is an optional | |
| // second fraction and we can skip this format. | |
| if (format.Match('F')) | |
| { | |
| format.GetRepeatCount(); | |
| break; | |
| } | |
| } | |
| result.SetBadDateTimeFailure(); | |
| return false; |
Line 4460 consumes the first F after the ., then line 4464 attempts to match a second F, which if not present results in the format exception from line 4470.