Calendar.WEEK_OF_YEAR无法正常运行。我的目标是每周一都是新的一周。我得到的结果是在代码注释中。
但我无法找到解决方案。
我的代码是:
Calendar cal = Calendar.getInstance();
//cal.setMinimalDaysInFirstWeek(7);
//cal.setFirstDayOfWeek(0);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("27/12/2014"); //SAT
Date d1 = sdf.parse("28/12/2014"); //SUN
cal.setTime(d);
Integer weekNumber1 = cal.get(Calendar.WEEK_OF_YEAR);
cal.setTime(d1);
Integer weekNumber2 = cal.get(Calendar.WEEK_OF_YEAR);
System.out.println( weekNumber1 );// 52
System.out.println( weekNumber2 );// 1`
第二个:
Calendar cal = Calendar.getInstance();
cal.setMinimalDaysInFirstWeek(7);
//cal.setFirstDayOfWeek(0);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("27/12/2014"); //SAT
Date d1 = sdf.parse("28/12/2014"); //SUN
cal.setTime(d);
Integer weekNumber1 = cal.get(Calendar.WEEK_OF_YEAR);
cal.setTime(d1);
Integer weekNumber2 = cal.get(Calendar.WEEK_OF_YEAR);
System.out.println( weekNumber1 );// 51
System.out.println( weekNumber2 );// 52
第三个:
Calendar cal = Calendar.getInstance();
cal.setMinimalDaysInFirstWeek(7);
cal.setFirstDayOfWeek(0);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("27/12/2014"); //SAT
Date d1 = sdf.parse("28/12/2014"); //SUN
Date d2 = sdf.parse("29/12/2014"); //Mon
cal.setTime(d);
Integer weekNumber1 = cal.get(Calendar.WEEK_OF_YEAR);
cal.setTime(d1);
Integer weekNumber2 = cal.get(Calendar.WEEK_OF_YEAR);
cal.setTime(d2);
Integer weekNumber3 = cal.get(Calendar.WEEK_OF_YEAR);
System.out.println( weekNumber1 );// 52
System.out.println( weekNumber2 );// 52
System.out.println( weekNumber3 );// 52
答案 0 :(得分:6)
您必须将星期一设置为日历的第一天。
cal.setFirstDayOfWeek(Calendar.MONDAY);