java 中怎么根据当前时间得到上周一和上周五的日期

2024-11-30 05:01:18
推荐回答(1个)
回答1:

/**
     * 获取上周五时间
     */
    public Date lastFirday() {
  //作用防止周日得到本周日期
        Calendar calendar = Calendar.getInstance();
        while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
            calendar.add(Calendar.DAY_OF_WEEK, -1);
        }
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        int offset = 7 - dayOfWeek;
        calendar.add(Calendar.DATE, offset - 9);
        return DateTimeUtil.getFirstDayOfWeek(calendar.getTime(), 6);//这是从上周日开始数的到本周五为6
    }
 
/**
     * 获取上周一时间
     */
    public Date lastMonday() {
        Calendar calendar = Calendar.getInstance();
        while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
            calendar.add(Calendar.DAY_OF_WEEK, -1);
        }
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        int offset = 1 - dayOfWeek;
        calendar.add(Calendar.DATE, offset - 7);
        return DateTimeUtil.getFirstDayOfWeek(calendar.getTime(), 2);
    }

参考http://www.cnblogs.com/mingtian521/p/3525870.html

请采纳,谢谢