Matthew Layton
Matthew Layton

Reputation: 42229

Java 8 Date API - Getting week of month throws UnsupportedTemporalTypeException: Unsupported field: DayOfWeek

I am trying to get the week of the current month like so:

YearMonth
    .from(Instant.now().atZone(ZoneId.of("UTC")))
    .get(WeekFields.ISO.weekOfMonth())

But this throws

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfWeek

I can't seem to work out why I'm getting this exception, because I'm not doing anything with DayOfWeek. Any ideas?

Upvotes: 6

Views: 1330

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201419

You can't get the week of the current month using YearMonth. It only has year and month. Change

YearMonth
    .from(Instant.now().atZone(ZoneId.of("UTC")))
    .get(WeekFields.ISO.weekOfMonth())

to

LocalDate
    .from(Instant.now().atZone(ZoneId.of("UTC")))
    .get(WeekFields.ISO.weekOfMonth())

And I get

1

Upvotes: 7

Related Questions