@Test
public void getWeekDate() throws IOException {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
int year = Integer.parseInt(sdf.format(date));
// 测试获取今年(2019)年的第二周的第一天和第二天
Date firstDayOfWeek = getFirstDayOfWeek(year, 2);
Date lastDayOfWeek = getLastDayOfWeek(year, 2);
System.out.println(formatDate(firstDayOfWeek));
System.out.println(formatDate(lastDayOfWeek));
/**
* 测试结果:
* 2019-01-07 00:00:00
* 2019-01-13 23:59:59
*/
}
/**
* 获取指定周的第一天
*
* @param year
* @param week
* @return
*/
public static Date getFirstDayOfWeek(int year, int week) {
Calendar cal = Calendar.getInstance();
// 设置年份
cal.set(Calendar.YEAR, year);
// 设置周
cal.set(Calendar.WEEK_OF_YEAR, week);
// 设置该周第一天为星期一
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
/**
* 获取指定周的最后一天
*
* @param year
* @param week
* @return
*/
public static Date getLastDayOfWeek(int year, int week) {
Calendar cal = Calendar.getInstance();
// 设置年份
cal.set(Calendar.YEAR, year);
// 设置周
cal.set(Calendar.WEEK_OF_YEAR, week);
// 设置该周第一天为星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
// 设置最后一天是星期日
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek() + 6); // Sunday
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}
/**
* 格式化日期
*
* @param date
* @return
*/
private static String formatDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}