我必须使用 SimpleDateFormat
在 Java 中解析日期。我正在使用一个现有的库,该库将日期作为 String
和一个 SimpleDateFormat
实例来解析它。
一切都很好,但如果日期格式仅包含自纪元时间 (1/1/1970) 以来的毫秒数,即以毫秒为单位的 UNIX 时间,我就会遇到麻烦。使用 new SimpleDateFormat("SS")
或 new SimpleDateFormat("SSS")
无效:
重现奇怪的 SimpleDateFormat
行为的代码:
TimeZone.setDefault(TimeZone.getTimeZone("GMT")); // just for the test
long currTimeInMilli = System.currentTimeMillis();
SimpleDateFormat msSDF = new SimpleDateFormat("SS"); // same result with SimpleDateFormat("SSS")
SimpleDateFormat secSDF = new SimpleDateFormat("ss");
System.out.println(msSDF.parse("" + currTimeInMilli));
System.out.println(secSDF.parse("" + (currTimeInMilli / 1000)));
System.out.println(new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy").format(currTimeInMilli));
产生的输出:
Mon Dec 15 07:46:20 GMT 1969 <-- should be like two other lines (?)!
Mon Apr 28 20:55:19 GMT 2014 <-- OK
Mon Apr 28 20:55:19 GMT 2014 <-- OK
这正常吗?我如何设置一个 SimpleDateFormat
能够解析自 epoch 以来经过的毫秒数?
注意事项:
- 我不能使用其他库,比如 Joda-time
- 我不能使用
new Date(long pNbMilli)
来构造日期(旧版库采用SimpleDateFormat
实例作为输入) - 我找到了这个 filed JDK bug但不确定它是否与此问题直接相关...
最佳答案
S
模式无法正确处理大于 Integer.MAX_VALUE
的毫秒数,这对于通常表示为 long 的数量来说可能看起来很奇怪。
如果您真的必须使用需要 DateFormat 的现有 API,您可以随时破解它:
SimpleDateFormat msSDF = new SimpleDateFormat("SSS") {
@Override
public Date parse(String source) throws ParseException {
return new Date(Long.parseLong(source));
}
};
(当然,可能还需要提供 format(string)
的 hacked 实现,具体取决于您的遗留 API 实际执行的操作。)
关于java - 只有毫秒的 SimpleDateFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23351335/