Languages
[Edit]
PT

Java 8 - Corrigir a Exceção quando usando LocalDateTime.now() formato com zona Z - java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: OffsetSeconds

3 points
Created by:
Alyona
1170

1. Descrição do problema.

Gostaria de formatar a data e a hora agora de LocalDateTime.now() com padrão de formatador. 

yyyy-MM-dd HH:mm Z

Código completo que lança UnsupportedTemporalTypeException: 

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatter_UnsupportedTemporalTypeException {

    public static void main(String[] args) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm Z");
        String format = fmt.format(LocalDateTime.now());
        System.out.println(format);
    }
}

Quando executo esse código, recebo este stacktrace:

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: OffsetSeconds
	at java.time.LocalDate.get0(LocalDate.java:680)
	at java.time.LocalDate.getLong(LocalDate.java:659)
	at java.time.LocalDateTime.getLong(LocalDateTime.java:720)
	at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
	at java.time.format.DateTimeFormatterBuilder$OffsetIdPrinterParser.format(DateTimeFormatterBuilder.java:3346)
	at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2190)
	at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746)
	at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720)

2. Solução.

// to solve this exception use:
ZonedDateTime.now()

// eg:
String format = fmt.format(ZonedDateTime.now());

// instead of using:
LocalDateTime.now()

Exemplo completo de código de trabalho:

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatter_UnsupportedTemporalTypeException_Solution {

    public static void main(String[] args) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm Z");
        String format = fmt.format(ZonedDateTime.now());
        System.out.println(format); // 2019-10-04 22:55 +0200
    }
}

Resultado:

2019-10-04 22:55 +0200

Referências:

  1. LocalDateTime.now() - Java docs
  2. UnsupportedTemporalTypeException - Java docs
  3. ZonedDateTime.now() - Java docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join