【问题标题】:SimpleDateFormat with only milliseconds只有毫秒的 SimpleDateFormat
【发布时间】: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


【解决方案1】:

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) 的黑客实现,这取决于您的旧 API 实际执行的操作。)

【讨论】:

  • 谢谢。好主意。那么不应该在SimpleDateFormat 中将其报告为错误吗?
猜你喜欢
  • 1970-01-01
  • 2011-11-01
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 2014-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多