简体   繁体   English

Java 8 Date&Time API:如何计算给定月份的ISO8601周?

[英]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? 是否有使用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. 但它给出了不正确的结果,例如在2014年3月5日它返回5,而根据ISO8601,3月只有4周。

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). (ISO-8601没有描述几个月内的方法 - 它只描述了几年内的方法)。

We can use the approach to find the 5th occurrence of Thursday, and see if it is in the same month: 我们可以使用该方法查找星期四的第5次出现,并查看它是否在同一个月:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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