Java 输入两个日期,计算出期间的周数
只要涉及到其他周的天,都算期间的周数:
static int calculate(Calendar c){
int dayForWeek;
if(c.get(Calendar.DAY_OF_WEEK) == 1){
dayForWeek = 7;
}else{
dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;}
return dayForWeek;
}
static Calendar From(Calendar c){
switch(calculate(c)){
case 1:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)-0);
break;
case 2:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)-1);
break;
case 3:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)-2);
break;
case 4:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)-3);
break;
case 5:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)-4);
break;
case 6:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)-5);
break;
case 7:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)-6);
}
return c;
}
static Calendar To(Calendar c){
switch(calculate(c)){
case 1:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)+6);
break;
case 2:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)+5);
break;
case 3:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)+4);
break;
case 4:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)+3);
break;
case 5:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)+2);
break;
case 6:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)+1);
break;
case 7:c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)+0);
}
return c;
}
static Long getResult(String startDate,String endDate) throws ParseException {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
c1.setTime(sdf.parse(startDate));
c2.setTime(sdf.parse(endDate));
long cc1=From(c1).getTimeInMillis()/(1000*3600*24);
long cc2=To(c2).getTimeInMillis()/(1000*3600*24);
return (cc2-cc1+1)/7;
}
测试:
刚好一周:
public static void main(String[] args) throws ParseException {
Long result = getResult("2020-02-10", "2020-02-16");
System.out.println("涉及的周数为:"+result);
}
刚好两周:
public static void main(String[] args) throws ParseException {
Long result = getResult("2020-02-10", "2020-02-23");
System.out.println("涉及的周数为:"+result);
}
两周再多两天:
public static void main(String[] args) throws ParseException {
Long result = getResult("2020-02-10", "2020-02-25");
System.out.println("涉及的周数为:"+result);
}