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.
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.
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
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.