1

How do I get the current time GMT date-time in RFC 822 / RFC 1123 format in Scala, to put into an HTTP header? Preferably using the built in Java 8 classes.

For some reason what I thought would be a simple generic task has eluded me.

Community
  • 1
  • 1
Rich Oliver
  • 6,001
  • 4
  • 34
  • 57

2 Answers2

4

You can use ZonedDateTime to get the current date time and DateTimeFormatter to format it using its existing formatter for RFC 822 / 1123: DateTimeFormatter.RFC_1123_DATE_TIME

import java.time.{ZonedDateTime, ZoneOffset}
import java.time.format.DateTimeFormatter

val datetime = ZonedDateTime.now(ZoneOffset.UTC)
val formatter = DateTimeFormatter.RFC_1123_DATE_TIME

datetime.format(formatter)
// String = Wed, 16 Sep 2015 21:45:10 GMT
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Peter Neyens
  • 9,770
  • 27
  • 33
0

Thanks to Peter Neyens for this answer which I've converted into a method, as I wanted as succinct as possible paste in code.

import java.time._ 
def nowHttp: String = "Date: " +
  ZonedDateTime.now(ZoneOffset.UTC).format(format.DateTimeFormatter.RFC_1123_DATE_TIME)

I've left off the "\r\n" for consistency as I use a specially defined operator to terminate and add an HTTP header line.

Rich Oliver
  • 6,001
  • 4
  • 34
  • 57