java - 只有毫秒的 SimpleDateFormat

标签 java datetime simpledateformat milliseconds

必须使用 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/

相关文章:

java - JXDatePicker 返回错误的日期

java - Java 日期解析异常

java - Glassfish 仅限于使用 JPA/EJB/Web 服务的两个同时线程

Java Lang 空指针异常,但我不明白为什么?

python - 在包含格式为 ('hour' 、 'min' 、 'AM/PM' 的时间元组的列表中查找时间的最大值

python - sqlalchemy:为什么我不能更新到 func.now(),但可以使用 'now()'?

java - 从 Android 中的 Date 对象获取日月的值?

java - 是否有折叠丰富的事件 :tree node?

java - 执行失败。使用 dex 转换应用程序类以进行调试

java - Simpledateformat 对称格式化/解析