Languages
[Edit]
PL

Java 8 poprawka dotycz─ůca wyj─ůtku podczas korzystania z formatu LocalDateTime.now() ze stref─ů Z - java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: OffsetSeconds

3 points
Created by:
Sylwia
3500

1. Opis problemu

Chciałbym teraz sformatować datę od LocalDateTime.now() ze wzorem formatyzatora 

yyyy-MM-dd HH:mm Z

Pe┼ény kod, kt├│ry zg┼éasza wyj─ůtek 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);
    }
}

Kiedy uruchamiam ten kod, otrzymuj─Ö nast─Öpuj─ůcy 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. Rozwi─ůzanie

// aby rozwi─ůza─ç ten wyj─ůtek u┼╝yj:
ZonedDateTime.now()

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

// zamiast u┼╝ywa─ç:
LocalDateTime.now()

Przyk┼éad pe┼énego dzia┼éaj─ůcego kodu:

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
    }
}

Wynik:

2019-10-04 22:55 +0200

Bibliografia

  1. LocalDateTime.now() - Java docs
  2. UnsupportedTemporalTypeException - Java docs
  3. ZonedDateTime.now() - Java docs
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join