/** * 获取给定年份的日历 * * @param year 年 * @return */ private Calendar getCalendarFormYear(int year) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); cal.set(Calendar.YEAR, year); return cal; }
/**
* 根据给定日期获取当前日期所属周数
*
* @param givenDate 日期
* @return
*/
public static Integer getWeekNo(String givenDate){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(givenDate);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setTime(date);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
/** * 获取给定周的开始日期
* * @param year 年 * @param weekNo 周 * @return */ public String getStartDayByWeekNo(int year, int weekNo) { Calendar cal = getCalendarFormYear(year); cal.set(Calendar.WEEK_OF_YEAR, weekNo); return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH); } /** * 获取给定周的结束日期 * * @param year 年 * @param weekNo 周 * @return */ public String getEndDayByWeekNo(int year, int weekNo) { Calendar cal = getCalendarFormYear(year); cal.set(Calendar.WEEK_OF_YEAR, weekNo); cal.add(Calendar.DAY_OF_WEEK, 6); return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH); }