我想知道当月的星期天数。例如,2019年3月有5个星期日,所以我想达到这个数字。 我已经尝试过在很多地方找到的这段代码,但是没有给出结果。
Calendar cal = Calendar.getInstance();
int mes_cal = cal.get(Calendar.MONTH);
int ano_cal = cal.get(Calendar.YEAR);
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int count = 0;
for (int day = 1; day <= daysInMonth; day++) {
cal.set(ano_cal, mes_cal, 1);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SUNDAY) {
count++;
System.out.println(count);
}
}
解决方案(来自@primo建议的链接,仅作了一项更正)
Calendar cal = Calendar.getInstance();
mes_cal = cal.get(Calendar.MONTH);
ano_cal = cal.get(Calendar.YEAR);
public int countDayOccurence(int year, int month,int dayToFindCount) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
int count = 0;
for (int day = 1; day <= daysInMonth; day++) {
calendar.set(year, month, day);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == dayToFindCount) {
count++;
}
}
return count;
}
然后调用方法
int countSunday = countDayOccurence(ano_cal,mes_cal,Calendar.SUNDAY);
答案 0 :(得分:0)
将日期作为校准设置中的第三个参数
Calendar cal = Calendar.getInstance();
int mes_cal = cal.get(Calendar.MONTH);
int ano_cal = cal.get(Calendar.YEAR);
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int count = 0;
for (int day = 1; day <= daysInMonth; day++) {
cal.set(ano_cal, mes_cal, day);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SUNDAY)
count++;
}
System.out.println("Total Sunday : "+count);
答案 1 :(得分:0)
function getNumberOFSundayInCurrent() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var cur_date = new Date(year,month,1);
var count = 0;
while (cur_date.getMonth() === month) {
if(cur_date.toLocaleDateString('en-US',{weekday:'long'}) === 'Sunday')
count += 1;
cur_date.setDate(cur_date.getDate() + 1);
}
return count;
}
console.log(getNumberOFSundayInCurrent());