我有一个File对象,我希望将该文件的最后修改日期转换为HTTP格式.格式是GMT时间,如:
Mon, 10 Feb 2014 16:17:37 GMT
Run Code Online (Sandbox Code Playgroud)
我知道java.io.File有一个lastModified()以毫秒为单位返回时间的方法.我也可以在毫秒内将该时间传递给java.util.Date类的构造函数.但是以HTTP格式获取字符串的最简单方法是什么?
谢谢.
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()));
Run Code Online (Sandbox Code Playgroud)
请阅读以下Joda-Time部分了解详细信息。Joda -Time项目现在处于维护模式,建议迁移到java.time类。
该类表示UTCInstant时间线上的时刻,分辨率为纳秒(最多九 (9) 位小数)。
long milliseconds = \xe2\x80\xa6 ; \nInstant instant = Instant.ofEpochMilli( milliseconds ); // Or use Instant.now() to experiment.\nRun Code Online (Sandbox Code Playgroud)\n如需格式化,请转换为OffsetDateTime.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );\nRun Code Online (Sandbox Code Playgroud)\n该类为您所需的格式DateTimeFormatter提供了现成的格式化程序。该格式由RFC 1123标准定义。
String output = odt.format ( DateTimeFormatter.RFC_1123_DATE_TIME );\nRun Code Online (Sandbox Code Playgroud)\n\n\n2017 年 1 月 11 日星期三 21:35:19 GMT
\n
对于其他格式化程序,我会说始终指定Locale. 但 RFC 1123 的特定格式化程序根据 RFC 要求硬编码为英语。因此指定 aLocale对输出没有影响。
只是为了好玩,这里有来自Meno Hochschild 正确答案的相同类型的代码,但使用的是Joda-Time 2.3 库。
\n一些注释\xe2\x80\xa6
\nlong(int64 位与 32 位)。 // Note how the variable for milliseconds is a "long" not "int".\nlong milliseconds = DateTime.now().getMillis(); // Get milliseconds from java.io.File method "lastModified", or wherever.\n\nDateTime dateTime = new DateTime( milliseconds, DateTimeZone.UTC );\nDateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE, dd MMM yyyy HH:mm:ss \'GMT\'" ).withZone( DateTimeZone.UTC ).withLocale( java.util.Locale.ENGLISH );\n\nString httpDateTime = formatter.print( dateTime );\nRun Code Online (Sandbox Code Playgroud)\n转储到控制台\xe2\x80\xa6
\nSystem.out.println( "milliseconds: " + milliseconds );\nSystem.out.println( "dateTime: " + dateTime );\nSystem.out.println( "httpDateTime: " + httpDateTime );\nRun Code Online (Sandbox Code Playgroud)\n当运行\xe2\x80\xa6时
\nlong milliseconds = \xe2\x80\xa6 ; \nInstant instant = Instant.ofEpochMilli( milliseconds ); // Or use Instant.now() to experiment.\nRun Code Online (Sandbox Code Playgroud)\nHTTP 1.1 规范确实需要该格式。所以如果你需要它,就使用它。但要知道,互联网社区已在很大程度上转向对当前一代协议使用更合理的ISO 8601格式。ISO 格式为YYYY-MM-DDTHH:MM:SS.ssssss+00:00,如上面输出的第二行所示。Joda-Time 库使用 ISO 8601 作为大多数用途的默认值。
| 归档时间: |
|
| 查看次数: |
863 次 |
| 最近记录: |