Java:HTTP格式的时间(以毫秒为单位)?

时间:2014-02-10 16:21:30

标签: java http date

我有一个File对象,我希望将该文件的最后修改日期转换为HTTP format。 格式为GMT时间,如:

Mon, 10 Feb 2014 16:17:37 GMT

我知道java.io.File有一个方法lastModified(),它以毫秒为单位返回时间。我也可以在毫秒内将该时间传递给java.util.Date类的构造函数。但是以HTTP格式获取字符串的最简单方法是什么?

感谢。

2 个答案:

答案 0 :(得分:5)

SimpleDateFormat sdf = 
  new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String httpDate = sdf.format(new Date(file.lastModified()));

答案 1 :(得分:4)

java.time

有关详细信息,请阅读以下Joda-Time部分。现在位于Joda-Timemaintenance mode项目建议迁移到java.time类。

Instant类代表UTC中时间轴上的一个时刻,分辨率为nanoseconds(小数部分最多九(9)位)。

long milliseconds = … ; 
Instant instant = Instant.ofEpochMilli( milliseconds );  // Or use Instant.now() to experiment.

要进行格式化,请转换为OffsetDateTime

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );

DateTimeFormatter课程提供ready-made formatter for your desired format。该格式由RFC 1123标准定义。

String output = odt.format ( DateTimeFormatter.RFC_1123_DATE_TIME );
  

2017年1月11日星期三21:35:19 GMT

对于其他格式化程序,我会说总是指定Locale。但RFC 1123的特定格式化程序根据RFC要求硬编码为英语。因此,指定Locale对输出没有影响。


约达时间

只是为了它,这是the correct answer by Meno Hochschild中使用Joda-Time 2.3库的相同类型的代码。

有几个笔记......

  • 在日期时间工作中,毫秒数必须是long而不是int(64位与32位)。
  • HTTP规范要求使用英语作为日期和月份的名称。因此,我们应该明确指定英语,以防我们的代码在JVM上运行,其中英语不是默认的Locale。

示例代码

 // Note how the variable for milliseconds is a "long" not "int".
long milliseconds = DateTime.now().getMillis(); // Get milliseconds from java.io.File method "lastModified", or wherever.

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 spec确实需要这种格式。因此,如果您需要它,请使用它。但是要知道,互联网社区已经基本上转向使用更合理的ISO 8601格式来生成当前的协议。 ISO格式为YYYY-MM-DDTHH:MM:SS.ssssss+00:00,如上面第二行输出所示。 Joda-Time库在大多数情况下使用ISO 8601作为默认值。