本文介紹了如何找到給定月份的周六和周日?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
限時(shí)送ChatGPT賬號(hào)..
我想找到給定月份的所有周六和周日.我該怎么做?
I want find all Saturdays and Sundays in A given month. How can I do so?
推薦答案
最簡(jiǎn)單的方法是遍歷一個(gè)月中的所有日子,并檢查每個(gè)日子的星期幾.例如:
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;
}
我絕對(duì)肯定有更有效的方法來(lái)做到這一點(diǎn) - 但這是我要開(kāi)始的,當(dāng)我發(fā)現(xiàn)它太慢時(shí)進(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.
請(qǐng)注意,如果您能夠使用 Joda Time,您的生活會(huì)輕松很多...
Note that if you're able to use Joda Time that would make your life a lot easier...
這篇關(guān)于如何找到給定月份的周六和周日?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!