java獲取指定日期所在周的 週一 和 週日

卓mu鳥發表於2020-10-30

獲取指定日期所在周的週一:

 /**
     * 獲取指定日期所在周的週一
     * 
     * @param date 日期
     */
    public static Date getFirstDayOfWeek(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            c.add(Calendar.DAY_OF_MONTH, -1);
        }
        c.add(Calendar.DATE, c.getFirstDayOfWeek() - c.get(Calendar.DAY_OF_WEEK) + 1);
        return c.getTime();
    }

獲取指定日期所在周的週日:

/**
     * 獲取指定日期所在周的週日
     * 
     * @param date 日期
     */
    public static Date getLastDayOfWeek(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        // 如果是週日直接返回
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            return date;
        }
        //System.out.println(c.get(Calendar.DAY_OF_WEEK));
        c.add(Calendar.DATE, 7 - c.get(Calendar.DAY_OF_WEEK) + 1);
        return c.getTime();
    }

測試:

public static void main(String[] args) {
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.DATE, 3);
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("當前日期:" + sf.format(c.getTime()));
		System.out.println(sf.format(getFirstDayOfWeek(c.getTime())));
		System.out.println(sf.format(getLastDayOfWeek(c.getTime())));
	}

結果:
在這裡插入圖片描述

參考:https://www.jianshu.com/p/b3bdd6c34e66

相關文章