Error java.time.format.DateTimeParseException: Failed to parse, not parsed text found in index 10

I try to execute the following line using LocalDateTime, but I always get an unparsed text error message:

Error java.time.format.DateTimeParseException: Text '2016-08-18 14:27:15.103+02' could not be parsed, unparsed text found at index 10

Here is my line: convertDate: ' 2016-08-18 14: 27: 15.103 + 02 '

And my code is:

public static LocalDate conversorStringToLocalDateTime(String convertDate) throws ParseException {
    LocalDate dateTime =LocalDate.parse(convertDate);
    return dateTime;
}

I think this is not too difficult, buy, I do not see a mistake. Could reason +02 per line?

+6
source share
2 answers

TL; DR

OffsetDateTime odt = OffsetDateTime.parse ( "2016-08-18 14:27:15.103+02" , DateTimeFormatter.ofPattern ( "yyyy-MM-dd HH:mm:ss.SSSX" ) ) ;

More details

greg-449 ( ), .

LocalDateTime, -UTC. A LocalDateTime , , .

+02 offset-from-UTC, " UTC ". , UTC 12 , 2 , 14 . . - , LocalDateTime, OffsetDateTime.

SQL, ISO 8601. SPACE T. java.time ISO 8601, .

String input = "2016-08-18 14:27:15.103+02";
String inputModified = input.replace ( " " , "T" );

, Java 8 , , . Java 9. Java 8 .

// Workaround for Java 8 where 2-digit offset fails parsing. Fixed in Java 9.
int lengthOfAbbreviatedOffset = 3;
if ( inputModified.indexOf ( "+" ) == ( inputModified.length () - lengthOfAbbreviatedOffset ) ) {
    // If third character from end is a PLUS SIGN, append ':00'.
    inputModified = inputModified + ":00";
}
if ( inputModified.indexOf ( "-" ) == ( inputModified.length () - lengthOfAbbreviatedOffset ) ) {
    // If third character from end is a PLUS SIGN, append ':00'.
    inputModified = inputModified + ":00";
}

.

OffsetDateTime odt = OffsetDateTime.parse ( inputModified );

. , +02 +02:00.

System.out.println ( "input: " + input + " | inputModified: " + inputModified + " | odt: " + odt );

: 2016-08-18 14: 27: 15.103 + 02 | inputModified: 2016-08-18T14: 27: 15.103 + 02: 00 | odt: 2016-08-18T14: 27: 15.103 + 02: 00

. - .

    DateTimeFormatter f = DateTimeFormatter.ofPattern ( "yyyy-MM-dd HH:mm:ss.SSSX" );
    OffsetDateTime odt = OffsetDateTime.parse ( input , f );

Postgres, , .

JDBC- JDBC 4.2, ResultSet::getObject, Instant OffsetDateTime. , ResultSet::getTimestamp, java.sql.Timestamp, java.time, toInstant Timestamp.

java.time -; java.sql .

+3

LocalDate, , , , .

, LocalDateTime, LocalDateTime.parse(String) ISO, , .

DateTimeFormatter, . - :

DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSX");
LocalDateTime result = LocalDateTime.parse(convertDate, format);
+5

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


All Articles