I'm trying to get a String of a date in Java in the format specified in HTTP 1.1. Which, as far as I can tell, is:
Fri, 31 Dec 1999 23:59:59 GMT
With the time always being GMT.
What would be the easiest way to get this from Date/Calendar/?
I'm trying to get a String of a date in Java in the format specified in HTTP 1.1. Which, as far as I can tell, is:
Fri, 31 Dec 1999 23:59:59 GMT
With the time always being GMT.
What would be the easiest way to get this from Date/Calendar/?
java.time
If you're using Java 8 and later you can the predefined formatter for RFC 1123,
DateTimeFormatter.RFC_1123_DATE_TIME
.In case someone else will try to find the answer here (like I did) here's what will do the trick:
in order to set the server to speak English and give time in GMT timezone.
You can play with it. The documentation is here: http://download.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Two-digit day-of-month
Some applications require the RFC1123 format to include a two digit day-of-month. The Java 8
DateTimeFormatter.RFC_1123_DATE_TIME
uses a single digit:Output:
Wed, 1 Aug 2018 14:56:46 GMT
Some applications don't like that. Before you use the old answers that use Joda-time or a pre-java8
SimpleDateFormat
, here's a working Java-8DateTimeFormatter
:DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss O")
Now, when you do this:
You get
Wed, 01 Aug 2018 14:56:46 GMT
- note the leading zero in the day-of-month field.If you, like me, are trying to format a Java 8
java.time.Instant
you need to explicitly add the time zone to the formatter. Like this:Which prints:
If you are not afraid of additional dependencies, you can use apache DateUtils:
This will format your date with respect to
RFC 822RFC1123.