Date HTTP header formatting

November 29th 2024 .NET Java

As we were implementing date formatting for the Date HTTP header in .NET, a Java developer warned us to double-check if we really want to use the built-in RFC 1123 format specifier for that. It turned out it is safe to do so in .NET, but you really shouldn't use the Java RFC 1123 formatter in this case.

Although they are both documented as an implementation of the RFC 1123 standard, they actually format the dates differently:

The difference is in the way the day of the month is formatted:

  • In .NET, two digits are always used.
  • In Java, one or two digits are used.

This results in a different output for the first 9 days of each month, e.g.,

  • .NET: Mon, 06 May 2024 03:05:07 GMT

RFC 1123 date formatting in .NET

  • Java: Mon, 6 May 2024 03:05:07 GMT

RFC 1123 date formatting in Java

According to RFC 9110, the .NET implementation is correct for the Date HTTP header: two digits must always be used.

This means that in .NET, the dates can simply be formatted using the R format specifier:

var formattedDate = date.ToString("R");

In Java, a custom formatter must be used instead of RFC_1123_DATE_TIME:

var formatter = DateTimeFormatter
    .ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.ENGLISH)
    .withZone(ZoneId.of("GMT"));  
var formattedDate = formatter.format(date);

Sample .NET and Java projects with tests are available in my GitHub repository. Feel free to run them yourself and see the difference in implementation.

I'm regularly working with both .NET and Java (although the former is my primary expertise). I've learned more than once that skills aren't always as easily transferrable as one might have expected. Which makes it all that more important to always validate your assumptions and cover your code with tests.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License