SimpleDateFormat显示分钟,秒和毫秒错误

我已经编写了这个示例程序,我希望将日期转换为另一种格式。 使用简单的日期格式时,我看不到预期的日期。

public class TestDate { /** * @param args */ public static void main(String[] args) { SimpleDateFormat originalformat = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSSSSS"); SimpleDateFormat targetformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS"); try { //Use Simple Date Format Date date = originalformat.parse("2015-04-09-17.18.48.677862"); System.out.println("Using SDF "+targetformat.format(date)); //Use Manual Translation String eventTime = "2015-04-09-17.18.48.677862"; StringBuffer timeBuffer = new StringBuffer(); for (int i = 0; i < eventTime.length(); i++) { if (i == 10) { timeBuffer.append(" "); continue; } else if (i == 13 || i == 16) { timeBuffer.append(":"); continue; } else { timeBuffer.append(eventTime.charAt(i)); } } timeBuffer.append("000"); String transformedTime = timeBuffer.toString().trim(); System.out.println("Manual Translation "+transformedTime); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

我看到以下输出。 第一个逻辑是使用简单的日期格式,第二个逻辑是手动翻译。

 Using SDF 2015-04-09 17:30:05.000862 Manual Translation 2015-04-09 17:18:48.677862000 

那么如何使简单的日期格式输出与手动值完全相似的值

看起来您不能使用6位数的毫秒数。 你的节目是11分17秒。 660秒= 11分钟,你有17秒的rest时间。 所以它只是将你的输入转换为几分钟,因为它不能接受超过3毫秒的数字。

根据SimpleDateFormat javadocs ,值677862被解释为毫秒,而不是微秒。 那是677秒,862毫秒。 秒部分为11分17秒,增加到17.18.48 ,变为17.30.05

要使用S格式,您将需要3位数的毫秒,而不是6.您需要将字符串截断为最后一个小数点后的3位数。