Getting inconsistent results with SimpleDateFormatter

Viewed 74

I am running below snippet and I am getting inconsistent resluts

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-M-dd HH:mm:ss.SSS");
         Date date;
         date = inputFormat.parse("2020-6-30 11:45:45. 123");
     SimpleDateFormat  outputFormat = new SimpleDateFormat("MM-dd-yy hh:mm:ss. SSS");
         System.out.println(outputFormat.format(date));//06-30-20 11:45:45. 123 is the output

Snippet 2:

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-M-dd HH:mm:ss.SSSSSS");
         Date date;
         date = inputFormat.parse("2020-6-30 11:45:45. 123456");
     SimpleDateFormat  outputFormat = new SimpleDateFormat("MM-dd-yy hh:mm:ss. SSSSSS");
         System.out.println(outputFormat.format(date));//06-30-20 11:47:48. 000456 is output

snippet 3:

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-M-dd HH:mm:ss.SSSSSSSSS");
         Date date;
         date = inputFormat.parse("2020-6-30 11:45:45. 123456789");
     SimpleDateFormat  outputFormat = new SimpleDateFormat("MM-dd-yy hh:mm:ss. SSSSSSSSS");
         System.out.println(outputFormat.format(date));//07-01-20 10:03:21. 000000789 is output

I believe the fraction seconds should be same before and after conversion. How can I achieve consistent results

2 Answers

The first one is correct, because your milliseconds are between 0 - 999. The second and third one are technically also correct, except your 123456 milliseconds are converted in 123 seconds + 456 milliseconds, which results in a time of +2 mins 03 secs.

So instead of trying to fix the output of simple date format, you have to fix the way you handle the input. Simple date format can not parse anything smaller than milliseconds. If you provide it with a number bigger than 999 milliseconds, it affects the seconds and so on...

Since you use java 8, I would VERY STRONGLY recommend abandoning horrible and outdated (no pun intended) SimpleDateFormat. It is not thread-safe, and the whole Date processing before java 8 needed to be rewritten badly. That's why there were external library alternatives that dealt with Date processing. (One well-known example is Joda time library). In Java 8 the Date processing has been majorly redesigned and re-written. So, please look up the packages java.time and all related ones java.time.*. Date formatting is done by DateTimeFormatter class. The recommendation is to switch to new Date processing packages. Note that all existing bugs will not be fixed for the old classes such as SimpleDateFormat

Related