Getting Date in HTTP format in Java

2019-01-11 09:25发布

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/?

8条回答
爷、活的狠高调
2楼-- · 2019-01-11 09:59

If you're using Joda-Time (which I would highly recommend for any handling of dates and times in Java), you can do:

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

...

private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER = 
    DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'")
    .withZoneUTC().withLocale(Locale.US);

...

RFC1123_DATE_TIME_FORMATTER.print(new DateTime())
查看更多
干净又极端
3楼-- · 2019-01-11 09:59

I know this is a late response but just wanted to add it for completeness.

You did not mention what you need the string for. But if you need it for an HTTP response header, you can use HttpServletResponse.setDateHeader(). It does all the formatting for you.

查看更多
登录 后发表回答