Error "could not be Parsed" when converting string to Datetime type

Asked

Viewed 3,489 times

1

I get a Date String like this:

2017-10-11 10:39:04.217923

I take that number off after the point, and I use the LocalDateTime.parse():

private final String PATTERN_DATA_HORA = "dd/MM/yyyy HH:mm:ss";

[...]

 Movimentacao movimentacao = new Movimentacao();
 StringTokenizer stringTokenizer = new StringTokenizer(movimentos.getJSONObject(i).get("dt_andamento_pa").toString());
 movimentacao.setData(LocalDateTime.parse(stringTokenizer.nextToken("."), DateTimeFormatter.ofPattern(PATTERN_DATA_HORA)).atOffset(ZoneOffset.UTC));

I have the following error in parse:

Text 2017-10-11 10:39:04 could not be Parsed at index 2.

Note: I have seen similar situations in gringos forums, but the error continues. What to do?

  • That one .217923 It’s a type of data designed to be accurate in nanoseconds. And if you parse in every string what happens, without taking the milliseconds in case?

  • Gives same error: java.time.format.Datetimeparseexception: Text '2017-10-11 10:39:04.217923' could not be Parsed at index 2

1 answer

5


This is happening because your Pattern does not reflect the received date format. You say that the string that will be converted (parse) has the format dd/MM/yyyy HH:mm:ss when in reality the format is yyyy-MM-dd HH:mm:ss.

We put the output format when we already have a Localdatetime and we want it to be displayed differently, see:

LocalDate hoje = LocalDate.now();
DateTimeFormatter formatador = DateTimeFormatter.ofPattern("dd/MM/yyyy");
hoje.format(formatador); // 11/08/2017

In your case you want to convert a string into a Localdatetime.

Heed! When placing LocalDateTime.parse(string,formatter).atOffset(ZoneOffset.UTC); you stop having as return a Localdatetime and you have an Offsetdatetime.

https://ideone.com/24ACmb

Browser other questions tagged

You are not signed in. Login or sign up in order to post.