以下是我用来计算一个月内的周数的代码。但实际上我需要几周的时间,每周的开始日为星期一,结束日为星期日。例如,2012年1月将有5周。但根据上述标准,它将有6周的时间
2012年1月
第一周 - 周日01
第二周 - 周一至周日2日
第三周 - 周一至周五9日
第四周 - 周一至周日16日至周日
第五周 - 周一至周日23日
第六周 - 周一至周三30周二。
以下代码仅提供5周。
public class Test {
public static void main(String[] args)
{
Calendar calendar = Calendar.getInstance();
int year = 2012;
int month = Calendar.JANUARY;
int date = 1;
calendar.set(year, month, date);
int numOfDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
int numOfWeeksInMonth = calendar.getActualMaximum(Calendar.WEEK_OF_MONTH);
System.out.println("Number of Days In Month: " + numOfDaysInMonth);
System.out.println("Number of Weeks In Month: " + numOfWeeksInMonth);
}
}
上述代码的输出为
月份天数:31
月份周数:5
但我需要得到“月中的周数:”为6 * 此外,我试图以ddMMYYYY格式获取每周的开始日期和结束日期。* 我还在努力。
有人可以帮我解决这个问题吗?
答案 0 :(得分:2)
添加此内容以获取"Number of Weeks In Month:" as 6
,
calendar.setFirstDayOfWeek(Calendar.MONDAY);
答案 1 :(得分:1)
尝试此功能
public static void main(String[] args) {
System.out.println(getNumberOfWeeks(2012, Calendar.JANUARY));
}
static int getNumberOfWeeks(int year, int month) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, 1);
int numOfWeeksInMonth = 1;
while (c.get(Calendar.MONTH) == month) {
c.add(Calendar.DAY_OF_MONTH, 1);
if (c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
numOfWeeksInMonth++;
}
}
return numOfWeeksInMonth;
}
答案 2 :(得分:1)
试试这个:
public static int noWeeks(int year,int month)
{
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, 1);
int initDay = c.get(Calendar.DAY_OF_WEEK)-1
;
int days = c.getActualMaximum(Calendar.DAY_OF_MONTH);
int a = (initDay==0?7:initDay)+days-1;
return a/7+(a%7==0?0:1);
}
答案 3 :(得分:0)
al algoritmocorretoéesseite:
public static int getTotalWeeksOfMonth(int month, int year){
int monthIndex = month-1;
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, monthIndex);
c.set(Calendar.DAY_OF_MONTH, 1);
int numOfWeeksInMonth = 0;
while (c.get(Calendar.MONTH) == monthIndex) {
c.add(Calendar.DAY_OF_MONTH, 1);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if ( dayOfWeek == Calendar.SUNDAY) {
numOfWeeksInMonth++;
}
}
if (c.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
numOfWeeksInMonth++;
}
return numOfWeeksInMonth;
}