本文介紹了如何找到給定月份的周六和周日?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
限時送ChatGPT賬號..
我想找到給定月份的所有周六和周日.我該怎么做?
I want find all Saturdays and Sundays in A given month. How can I do so?
推薦答案
最簡單的方法是遍歷一個月中的所有日子,并檢查每個日子的星期幾.例如:
The simplest way is to just iterate over all the days in the month, and check the day of week for each of them. For example:
// 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;
}
我絕對肯定有更有效的方法來做到這一點(diǎn) - 但這是我要開始的,當(dāng)我發(fā)現(xiàn)它太慢時進(jìn)行優(yōu)化.
I'm absolutely sure there are far more efficient ways of doing this - but that's what I'd start with, and optimize when I'd found it's too slow.
請注意,如果您能夠使用 Joda Time,您的生活會輕松很多...
Note that if you're able to use Joda Time that would make your life a lot easier...
這篇關(guān)于如何找到給定月份的周六和周日?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!