Search code examples
c#datetimeopenapirfc3339

ParseExact cannot parse a string in RFC 3339 Internet Date/Time format


It seems that C# does not manage to parse a time in a valid RFC 3339 format:

DateTime.ParseExact("2019-12-31T00:00:00.123456789+01:00", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffffzzz", null)

This line throws an exception, while this line works just fine:

DateTime.ParseExact("2019-12-31T00:00:00.1234567+01:00", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz", null)

So it seems there is a limit on milliseconds, but I cannot find out any documentation on that. Is this how it is supposed to be?


The reason want to parse this date is that I have have an input date field. We use OAS (Swagger) date-time format that quite clearly says that any date in RFC 3339 Internet Date/Time format should be valid. Now from the spec here section 5.6

time-secfrac    = "." 1*DIGIT

As far as I understand this means that up to 9 digits should be allowed and to be 100% compliant we have to allow these inputs, but it does not seem that C# even supports that.

Any ideas on how to fix it?


Solution

  • Per MSDN specification, you can use only fffffff

    The fffffff custom format specifier represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value.

    In your first example

    DateTime.ParseExact("2019-12-31T00:00:00.123456789+01:00", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffffzzz", null)
    

    you are using fffffffff which is more precise for .NET custom date and time format strings