2

below piece of code thorws exception..am i doing something wrong here?

DateTimeFormatter  FORMATTER    = DateTimeFormatter.ofPattern(
                                        "ddMMuuuuHHmmssSSS"
                                    );      
    String currentTime=FORMATTER.format(LocalDateTime.now());
    System.out.println(currentTime);
    LocalDateTime parsedTime=LocalDateTime.parse(currentTime,FORMATTER);


09042016161444380
Exception in thread "main" java.time.format.DateTimeParseException: Text '09042016161444380' could not be parsed at index 4
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
Krishan
  • 56
  • 5
  • 3
    I *suspect* the problem is that the parser doesn't know where the year is going to stop - it could be 20161 rather than 2016. If you add a `'T'` between the date and time parts, it works. Personally I'd strongly advise you to use an ISO-8601 format if at all possible... – Jon Skeet Apr 09 '16 at 10:57
  • thanks Jon but parser should read the pattern which says that year is 4 char, hence should stop at 2016. – Krishan Apr 09 '16 at 11:02
  • 3
    @Krishan no, not exactly. 4 or more means interpret the year literally, so it would parse the year as `2016161444380` - which is quite far in the future. – Boris the Spider Apr 09 '16 at 11:49

1 Answers1

2

As Jon Skeet mentioned in the above comment, with uuuu the parser doesn't know where the year is going to stop. This is because more than 2 u's or y's are interpreted literally by the parser.

From JavaDoc of Year:

For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D.

Hence, it should work fine if you change it to ddMMuuHHmmssSSS or ddMMyyHHmmssSSS from ddMMuuuuHHmmssSSS as in this instance the parser knows where to stop exactly.

Community
  • 1
  • 1
user2004685
  • 9,548
  • 5
  • 37
  • 54