Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

date

kotlin

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?

like image 900
Matthew Layton Avatar asked Jan 05 '19 02:01

Matthew Layton


1 Answers

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
like image 183
Elliott Frisch Avatar answered Nov 04 '22 00:11

Elliott Frisch