解决对给定一个时间段补全成整周并且按中国周分割时间的问题
问题:
最近项目维护遇到客户提的一个需求,原来项目中有一个日报功能,现在客户需要将日报改为周报。
要求:给定一个时间段(时间不超过30天),要求将时间补成整周按周分割并且得到该周为几几年几月第几周。周一为一周的开始,如果周跨月的话,按周一所在的月计算。
解决方案:
1 将时间补为整周
-
向前补齐
public String roundForward(String beginTime) throws ParseException { final int monday = 2; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse(beginTime); Calendar calendar = Calendar.getInstance(); calendar.setFirstDayOfWeek(Calendar.MONDAY); calendar.setTime(date); if (calendar.get(Calendar.DAY_OF_WEEK) != monday){ int dayWeek = calendar.get(Calendar.DAY_OF_WEEK); if(dayWeek==1){ dayWeek = 8; } calendar.add(Calendar.DATE,-(dayWeek-2)); System.out.println(sdf.format(calendar.getTime())); beginTime = sdf.format(calendar.getTime()); } return beginTime; }
-
向后补齐
public String roundBackward(String endTime) throws ParseException { final int sunday = 1; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse(endTime); Calendar calendar = Calendar.getInstance(); calendar.setFirstDayOfWeek(Calendar.MONDAY); calendar.setTime(date); if (calendar.get(Calendar.DAY_OF_WEEK) != sunday){ int dayWeek = calendar