SimpleDateFormat showing minutes, seconds and milliseconds wrong

谁说胖子不能爱 提交于 2019-12-29 10:06:27

问题


I have written this sample program where I want to convert a date into another format. I don't see the expected date when using simple date format.

 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();
        }
    }

}

I see the following outputs. The first logic is using simple date format and the second one is manual translation.

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

So How to make the simple date format to output a exactly similar value like the manual one


回答1:


It would appear that you can't use 6 digits for the milliseconds. Your program is 11 minutes and 17 seconds off. 660 seconds = 11 minutes and you have 17 seconds off. So its just converting your input into minutes from seconds since it can't accept more than 3 milliseconds digits.




回答2:


The value 677862 is being interpreted as milliseconds, as per the SimpleDateFormat javadocs, not as microseconds. That is 677 seconds, 862 milliseconds. The seconds part is 11 minutes and 17 seconds, which is added to 17.18.48 to become 17.30.05.

To work with the S format, you will need 3 digits for the milliseconds, not 6. You will need to truncate your string to 3 digits past the last decimal point.



来源:https://stackoverflow.com/questions/29828447/simpledateformat-showing-minutes-seconds-and-milliseconds-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!