简体   繁体   中英

Java 8 Date & Time API: How to get count of ISO8601 weeks in given month?

Now I just count number of Thursdays in period from 1st to last date. Is there one line solutions using Java 8 Date & Time API? I've tried:

date.range(WeekFields.ISO.weekOfMonth()).getMaximum(); 

but it gives incorrect result, for example for March,5,2014 it returns 5 while March has only 4 weeks according to ISO8601.

Lets state the question as "how many Thursdays are there in a given month"?

(ISO-8601 does not describe an approach for weeks within months - it only describes an approach for weeks within years).

We can use the approach to find the 5th occurrence of Thursday, and see if it is in the same month:

LocalDate date = ...
LocalDate fifthThu = date.with(TemporalAdjusters.dayOfWeekInMonth(5, THURSDAY));
int thursdays = (fifthThu.getMonth() == date.getMonth() ? 5 : 4);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM