java.time
阅读下面的Joda-Time
部分了解详情。Joda-Time项目现在处于维护模式,建议迁移到java.time类。
Instant
类表示时间线上的一个时刻,以UTC为基准,精度为纳秒(最多九个小数位)。
long milliseconds = … ;
Instant instant = Instant.ofEpochMilli( milliseconds ); // Or use Instant.now() to experiment.
对于格式化,请转换为OffsetDateTime
。
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
DateTimeFormatter
类提供了一个预定义的格式化程序,以满足您所需的格式要求。该格式由RFC 1123标准定义。
String output = odt.format ( DateTimeFormatter.RFC_1123_DATE_TIME );
2017年1月11日21:35:19 GMT
对于其他格式化程序,我会建议始终指定Locale
。但是,针对RFC 1123的特定格式化程序根据RFC要求硬编码为英语。因此,指定Locale
对输出没有影响。
Joda-Time
仅仅为了好玩,这里是与Meno Hochschild的正确答案相同类型的代码,但使用了Joda-Time 2.3库。
一些注意事项...
- 在日期时间处理中,毫秒数必须是
long
而不是int
(64位 vs 32位)。
- HTTP规范要求使用英语来表示星期和月份的名称。因此,我们应该明确地指定英语,以防我们的代码在默认语言不是英语的JVM上运行。
示例代码
long milliseconds = DateTime.now().getMillis();
DateTime dateTime = new DateTime( milliseconds, DateTimeZone.UTC );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE, dd MMM yyyy HH:mm:ss 'GMT'" ).withZone( DateTimeZone.UTC ).withLocale( java.util.Locale.ENGLISH );
String httpDateTime = formatter.print( dateTime );
转储到控制台...
System.out.println( "milliseconds: " + milliseconds );
System.out.println( "dateTime: " + dateTime );
System.out.println( "httpDateTime: " + httpDateTime );
运行时...
milliseconds: 1392075528617
dateTime: 2014-02-10T23:38:48.617Z
httpDateTime: Mon, 10 Feb 2014 23:38:48 GMT
ISO 8601
该格式确实是HTTP 1.1规范所要求的。因此,如果您需要它,请使用它。但请知道,互联网社区已经大量使用更为合理的ISO 8601格式来支持当前一代协议。ISO格式为YYYY-MM-DDTHH:MM:SS.ssssss+00:00
,如上面第二行输出所示。Joda-Time库在大多数情况下将ISO 8601用作其默认设置。