Skip to content

Bug in DateTime format handling for ".F", optional fractional seconds. #120468

@MarkPflug

Description

@MarkPflug

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:

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions