DE
Java 8 Korrektur für Ausnahme bei Verwendung des LocalDateTime.now() Formats mit Zone Z - java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: OffsetSeconds
6
points
1. Problembeschreibung
Ich will aktuelle Datum und Uhrzeit aus LocalDateTime.now()
mit Formatierungsmuster formatieren.
yyyy-MM-dd HH:mm Z
Vollständiger Code, der UnsupportedTemporalTypeException wirft:
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);
}
}
Wenn ich diesen Code ausführe, dann erhalte ich diesen 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. Lösung
// Um diese Ausnahme zu lösen, soll man Folgendes verwenden:
ZonedDateTime.now()
// z.B:
String format = fmt.format(ZonedDateTime.now());
// anstatt es zu verwenden:
LocalDateTime.now()
Beispiel für einen vollständigen funktionierenden Code:
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
}
}
Ausgabe:
2019-10-04 22:55 +0200