Java.text.ParseException: Unbeatable Date: yyyy-MM-dd HH: mm: ss.SSSSSS

I get a ParseException for the following code

  String dateStr = "2011-12-22 10:56:24.389362"; String formatStr = "yyyy-MM-dd HH:mm:ss.SSSSSS"; Date testDate = null; SimpleDateFormat sdf= new SimpleDateFormat(formatStr); sdf.setLenient(false); testDate = sdf.parse(dateStr); System.out.println("CHECK DATE " + sdf.format(testDate)); 

Exception in thread "main" java.text.ParseException: Unparseable date: "2011-12-22 10:56:24.389362" at java.text.DateFormat.parse(DateFormat.java:337)

If I comment on the line sdf.setLenient(false) , then I see the time difference in the output of CHECK DATE 2011-12-22 11:02:53.000362

What am I doing wrong?

+6
source share
5 answers

'S' is a millisecond. From time to time it is 1000 (0 to 999) milliseconds. 389362 is greater than 999. An additional 389000 milliseconds are converted to 389 seconds or 6 minutes 29 seconds and added to the time.

+7
source

S format S refers to milliseconds. When you enable soft parsing, the last part is interpreted as 389362 milliseconds. When this is added to the date so far, the last 3 digits (in fact, the value of% 1000) become the actual milliseconds, and you end up with a date of about 389 seconds (~ 6 1/2 minutes) later than you expect (With strict In the analysis, the parser knows that 389362 milliseconds does not make sense, so it throws an error.)

The easiest way to get around this, if you can guarantee that the date will always look like this, is to chop off the last 3 digits. (This will give you a millisecond date in about half the time, but it's better than writing a date parser ...)

+4
source

Your millisecond data entry is incorrect. It should be: -

String dateStr = "2011-12-22 10:56:24.389";

You also do not need the extra amount of "S" in the template. It should be enough:

String formatStr = "yyyy-MM-dd HH:mm:ss.S";

The java docs text clearly states for the presentation type Number :

Number: for formatting, the number of letters of the template is the minimum number of digits and shorter numbers with zero sum. For parsing, the number of pattern letters is ignored unless it is necessary to separate two adjacent fields.

This works when you set lenient to true (or comment out the line that matches it by default), as you ask the parser to not be too strict in parsing. From java docs to setLenient () : -

Specify whether to parse date and time parsing. With soft parsing, the analyzer can use heuristics to interpret inputs that do not exactly match this object. With strict parsing, Inputs must match this object.

+3
source

S used only for milliseconds . If you need microseconds, you will have to write your own parser.

+2
source

Use toISOString('HH:mm:ss.S') to get the milliseconds (3 digits), then fill in as you need with 0.

For instance:

 new Date().toISOString('HH:mm:ss.S') 

returns "2012-02-10T12: 16: 39.124Z"

0
source

Source: https://habr.com/ru/post/904331/


All Articles