【发布时间】:2014-04-28 21:16:29
【问题描述】:
我必须使用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
正常吗?如何设置一个能够解析自 epoch 以来经过的毫秒数的 SimpleDateFormat?
注意事项:
- 我无法使用 Joda-time 等其他库
- 我不能使用
new Date(long pNbMilli)来构造日期(旧库将SimpleDateFormat实例作为输入) - 我发现了这个filed JDK bug,但不确定它是否与这个问题直接相关...
【问题讨论】:
-
并且不允许使用日历?
-
@Rod_Algonquin nope :(
标签: java datetime simpledateformat milliseconds