Java 8 formatting date-time incorrect behavior

I have the following code snippet that throws DateTimeParseException:

String dateString = "Jul 20 09:32:46"
DateTimeFormatter formatter=DateTimeFormatter.ofPattern("L d HH:mm:ss");
return ZonedDateTime.parse(dateString, formatter);

According to the documentation, you will notice that this Julis an example for a symbol L.

However, the exception message:

java.time.format.DateTimeParseException: text 'Jul' cannot be parsed with index 0

What am I missing?

+4
source share
2 answers

You have some problems here:

  • To properly parse "July", you should use MMMinstead L( here ).
  • Your date string does not have a year. You cannot create ZonedDateTime without a year.
  • Zoned date, , . LocalDateTime, .

:

:

String dateString = "Jul 20 2018 09:32:46+0000";
DateTimeFormatter formatter= DateTimeFormatter.ofPattern("MMM dd y H:mm:ssZ");
return ZonedDateTime.parse(dateString, formatter);

:

String dateString = "Jul 20 2018 09:32:46";
DateTimeFormatter formatter= DateTimeFormatter.ofPattern("MMM dd y H:mm:ss");
return LocalDateTime.parse(dateString, formatter);
+6

. : , , , .

    String dateString = "Jul 20 2018 09:32:46 America/Argentina/La_Rioja";
    DateTimeFormatter formatter 
            = DateTimeFormatter.ofPattern("LLL d uuuu HH:mm:ss VV", Locale.ROOT);
    System.out.println(ZonedDateTime.parse(dateString, formatter));

2018-07-20T09:32:46-03:00[America/Argentina/La_Rioja]

Jul 20 2018 09:32:46 -08:30 ZonedDateTime 2018-07-20T09: 32: 46-08: 30.

. "Jul" , , , , , - . . Locale.getDefault(). ( ), .

, M L / 7; 07; ; ; J. : " /: 3 , . ". "Jul" - , 3 . " 4 ". "Jul" , .

Java 9.0.4, , MMM LLL . jdk1.8.0_131 MMM, LLL , ( Mac). . M L.

,

    String dateString = "Jul 20 09:32:46";
    ZoneId zone = ZoneId.of("America/Argentina/La_Rioja");
    DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("LLL d HH:mm:ss")
            .parseDefaulting(ChronoField.YEAR, Year.now(zone).getValue())
            .toFormatter(Locale.ROOT)
            .withZone(zone);
    System.out.println(ZonedDateTime.parse(dateString, formatter));

2018-07-20T09:32:46-03:00[America/Argentina/La_Rioja]. , , , . , .

Java 8 MMM, LLL.

+2

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


All Articles