gpt4 book ai didi

java - 如何找到给定月份的星期六和星期日?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:22:01 25 4
gpt4 key购买 nike

我想找到给定月份的所有星期六和星期日。我该怎么做?

最佳答案

最简单的方法是遍历一个月中的所有日子,并检查每一天是星期几。例如:

// This takes a 1-based month, e.g. January=1. If you want to use a 0-based
// month, remove the "- 1" later on.
public int countWeekendDays(int year, int month) {
Calendar calendar = Calendar.getInstance();
// Note that month is 0-based in calendar, bizarrely.
calendar.set(year, month - 1, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

int count = 0;
for (int day = 1; day <= daysInMonth; day++) {
calendar.set(year, month - 1, day);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SUNDAY || dayOfweek == Calendar.SATURDAY) {
count++;
// Or do whatever you need to with the result.
}
}
return count;
}

绝对确定有更有效的方法来做到这一点——但这就是我开始的方式,并在我发现它太慢时进行优化。

请注意,如果您能够使用 Joda Time那会让你的生活更轻松......

关于java - 如何找到给定月份的星期六和星期日?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9909361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com