0

I am trying to parse the current timestamp with specific format but every try I keep getting a java.time.format.DateTimeParseException. My code:

ZonedDateTime.parse(
    ZonedDateTime.now().toString(),
    DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss.SSS")
            .withZone(ZoneId.of("UTC")) //I also tried ZoneId.systemDefault()
)

Result:

java.time.format.DateTimeParseException:
Text '2018-02-27T11:01:18.776+01:00[Europe/Berlin]' could not be parsed at index 2

The question is why I can't parse it in the desired format and how to achieve it?

P.S. I also saw this post and tried setting the ZoneId but it didn't help.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Arthur Eirich
  • 3,368
  • 9
  • 31
  • 63

4 Answers4

2

To parse the result from ZonedDateTime.toString() back you don’t need an explicit formatter at all:

    System.out.println(ZonedDateTime.parse(
            ZonedDateTime.now(ZoneId.of("Asia/Kuala_Lumpur")).toString()));

This printed

2018-02-27T21:48:16.214832+08:00[Asia/Kuala_Lumpur]

The formatter from your question works nicely for formatting:

    System.out.println(ZonedDateTime.now(ZoneId.of("Asia/Kuala_Lumpur"))
            .format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss.SSS")));

This printed:

27.02.2018 21:48:16.237

Did you confuse the word usage? Parsing means analyzing a string in order to make sense of it, in this case converting it to a date-time object like ZonedDateTime. The opposite conversion is called formatting, converting the date-time object into a string in a specific format, typically for human readability or data interchange.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

The DateTimeFormat

"dd.MM.yyyy HH:mm:ss.SSS"
does not match with
'2018-02-27T11:01:18.776+01:00[Europe/Berlin]'
produced by
ZonedDateTime.now().toString()
Mark Schäfer
  • 925
  • 1
  • 12
  • 23
0

This should work for converting the now() result String --> Date, as the right formatter is already in the JDK:

String inputStr = ZonedDateTime.now().toString();
ZonedDateTime parsed = ZonedDateTime.parse(inputStr, DateTimeFormatter.ISO_DATE_TIME) 


System.out.println(parsed);

If you want to go the otheway around you convert the Date --> String via

 DateTimeFormatter pattern = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss.SSS");

        String parsed = pattern.format(ZonedDateTime.now());
        System.out.println(parsed);
lwi
  • 1,682
  • 12
  • 21
0

You can directly use the format function of the ZonedDateTime. For example:

String dateString = ZonedDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);

You can as well look at:

Stefan Großmann
  • 866
  • 9
  • 20