java获取日期所在周第一天和最后一天

//获取日期所在周的周一的日期
public static String getWeekfirstday(String day) throws Exception{

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    cal.setTime(sdf.parse(day));

    int weekday = cal.get(Calendar.DAY_OF_WEEK);//当前日期是周几
    if(weekday == 1){//如果是周日,减一
        cal.add(Calendar.DAY_OF_MONTH,-1);
    }
    cal.setFirstDayOfWeek(Calendar.MONDAY);//周一
    int dy = cal.get(Calendar.DAY_OF_WEEK);
    cal.add(Calendar.DATE,cal.getFirstDayOfWeek() - dy);

    return sdf.format(cal.getTime());
}

//获取日期所在周的周日的日期
public static String getWeeklastday(String day) throws Exception{

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    cal.setTime(sdf.parse(day));

    int weekday = cal.get(Calendar.DAY_OF_WEEK);//当前日期是周几
    if(weekday != 1){
        cal.add(Calendar.DATE,8 - weekday);
        return sdf.format(cal.getTime());
    }

    return sdf.format(cal.getTime());
}

你可能感兴趣的:(工具类,java,java获取周一和周日)