Error "could not be parsed" when converting string to DateTime type

1

I get a DataHora String like this:

  

2017-10-11 10: 39: 04.217923

I remove this number after the period, and I use 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 parse error:

  

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

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

    
asked by anonymous 11.10.2017 / 17:38

1 answer

5

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

We put the output format when we already have a LocalDateTime and 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 to a LocalDateTime.

Caution! When you put LocalDateTime.parse(string,formatter).atOffset(ZoneOffset.UTC); you no longer have a LocalDateTime as a return and have an OffsetDateTime.

link

    
11.10.2017 / 19:04