英文:
how to get how many Friday available in each month using each month of LocalDate in java 8?
问题
我想要每个月可用的总星期五的数量。如何获得?
- 代码
private static int getFridayCount(DayOfWeek dayOfWeek, LocalDate startDate) {
return //
}
英文:
I want count of total Friday available in each month. How to get that?
1.code
private static int getFridayCount(DayOfWeek dayOfWeek, LocalDate startDate) {
return //
}
答案1
得分: 4
可能不是最快的方法,但我觉得这个非常简单易懂:
public static int numberOfDaysOfWeekInMonth(DayOfWeek dow, YearMonth yearMonth) {
LocalDate startOfMonth = yearMonth.atDay(1);
LocalDate first = startOfMonth.with(TemporalAdjusters.firstInMonth(dow));
LocalDate last = startOfMonth.with(TemporalAdjusters.lastInMonth(dow));
return (last.getDayOfMonth() - first.getDayOfMonth()) / 7 + 1;
}
示例用法:
System.out.println(
numberOfDaysOfWeekInMonth(
DayOfWeek.FRIDAY, YearMonth.of(2020, 9)
)
); // 输出 4
英文:
Probably not the fastest, but I find this really simple to understand:
public static int numberOfDaysOfWeekInMonth(DayOfWeek dow, YearMonth yearMonth) {
LocalDate startOfMonth = yearMonth.atDay(1);
LocalDate first = startOfMonth.with(TemporalAdjusters.firstInMonth(dow));
LocalDate last = startOfMonth.with(TemporalAdjusters.lastInMonth(dow));
return (last.getDayOfMonth() - first.getDayOfMonth()) / 7 + 1;
}
Example usage:
System.out.println(
numberOfDaysOfWeekInMonth(
DayOfWeek.FRIDAY, YearMonth.of(2020, 9)
)
); // outputs 4
答案2
得分: 1
你可以从startDate
到月底计算每个dayOfWeek
的次数,如下所示:
import java.time.*;
public class Main {
public static void main(String[] args) {
DayOfWeek dow = DayOfWeek.FRIDAY;
LocalDate startDate = LocalDate.of(2020, 9 ,25);
System.out.println("Amount: " + getCountOfDayInMonth(dow, startDate));
}
private static int getCountOfDayInMonth(DayOfWeek dow, LocalDate startDate) {
LocalDate date = startDate;
int count = 0;
while (date.getMonth() == startDate.getMonth()) {
if (date.getDayOfWeek() == dow) {
count++;
}
date = date.plusDays(1);
}
return count;
}
}
其中date
是从startDate
开始,持续到当前月份的LocalDate
。
英文:
You may count every dayOfWeek
from startDate
to end of month like
import java.time.*;
public class Main {
public static void main(String[] args) {
DayOfWeek dow = DayOfWeek.FRIDAY;
LocalDate startDate = LocalDate.of(2020, 9 ,25);
System.out.println("Amount: " + getCountOfDayInMonth(dow, startDate));
}
private static int getCountOfDayInMonth(DayOfWeek dow, LocalDate startDate) {
LocalDate date = startDate;
int count = 0;
while (date.getMonth() == startDate.getMonth()) {
if (date.getDayOfWeek() == dow) {
count++;
}
date = date.plusDays(1);
}
return count;
}
}
Where date
is a LocalDate
beginning at startDate
and going through the current Month
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论