Exception in thread “main” java.time.temporal.UnsupportedTemporalTypeException Unsupported field ClockHourOfAmPm

I have the following code. When I try to run it, it throws an exception.

LocalDate localDate = LocalDate.now();
DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd hh:mm:ss");
String date = dtFormatter.format(localDate);

Exception:

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: ClockHourOfAmPm
	at java.base/java.time.LocalDate.get0(LocalDate.java:709)
	at java.base/java.time.LocalDate.getLong(LocalDate.java:688)
	at java.base/java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:308)
	at java.base/java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2704)
	at java.base/java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2343)
	at java.base/java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1847)
	at java.base/java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1821)
    at com.SDK.main(SDK.java:22)
  1. Accepted Answer

Accepted Answer

You are using LocalDate in the first line of code, which does not store or provide time. In your formatter, you are using time "yyyy-MMM-dd hh:mm:ss" and that’s why you’re getting the exception.

LocalDate is date-only and is used for things like birthdays e.g. 2007-12-03 but not for representing an time. If you want to use time, use LocalDateTime class instead.

LocalDateTime localDate = LocalDateTime.now(); // fixed: LocalDateTime
DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd hh:mm:ss");
String date = dtFormatter.format(localDate);
System.out.println(date);

Speak Your Mind