SimpleDateFormat格式从毫秒中删除前导零

时间:2014-07-07 13:16:09

标签: java

我在使用SimpleDateFormat形成毫秒时遇到困难。我正在尝试使用模式“SS”获得精确的毫秒输出,但是当毫秒开始时,SimpleDateFormat.format()将删除前导零并返回剩余数字。

例如,我希望得到“08”的输出,但是从时间02:20:48.087得到“87”,格式为“SS”或“S”。

在javadoc中,声明两个字母模式输出被解释为数字,但同样的问题也出现在一个S字母上。

SimpleDateFormat test = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
Calendar testCalendar = Calendar.getInstance();
long unixtime = 435457248087L; // 1983-10-20 02:20:48.087
testCalendar.setTimeInMillis(unixtime);

String output = test.format(testCalendar.getTime());
System.out.println(output); // outputs 1983-10-20 02:20:48.87, not xxx.08

使用“SSS”模式当然可以很容易地解决这个问题,但我只是好奇这是一个错误还是这个错误。

1 个答案:

答案 0 :(得分:4)

SS只是“毫秒数,如果需要0填充,可以给出2位数的结果”。所以它看起来像文档所期望的那样。

我个人认为如果指定(并实施)将08作为秒到2位小数的分数会更加明智 - 不幸的是,它不是如何运作的。

认为没有任何方法可以使用SimpleDateFormat指定“小数点后两位”。