1. 程式人生 > >Java獲取本週一、上週一、下週一時間

Java獲取本週一、上週一、下週一時間

原理不多說,獲取本週一時間,然後+/-1就是下週/上週一的時間

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTest {
	public static Date geLastWeekMonday(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(getThisWeekMonday(date));
		cal.add(Calendar.DATE, -7);
		return cal.getTime();
	}

	public static Date getThisWeekMonday(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		// 獲得當前日期是一個星期的第幾天
		int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
		if (1 == dayWeek) {
			cal.add(Calendar.DAY_OF_MONTH, -1);
		}
		// 設定一個星期的第一天,按中國的習慣一個星期的第一天是星期一
		cal.setFirstDayOfWeek(Calendar.MONDAY);
		// 獲得當前日期是一個星期的第幾天
		int day = cal.get(Calendar.DAY_OF_WEEK);
		// 根據日曆的規則,給當前日期減去星期幾與一個星期第一天的差值
		cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
		return cal.getTime();
	}

	public static Date getNextWeekMonday(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(getThisWeekMonday(date));
		cal.add(Calendar.DATE, 7);
		return cal.getTime();
	}

	public static void main(String[] args) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date date = sdf.parse("2017-09-10");
			System.out.println("今天是" + sdf.format(date));
			System.out.println("上週一" + sdf.format(geLastWeekMonday(date)));
			System.out.println("本週一" + sdf.format(getThisWeekMonday(date)));
			System.out.println("下週一" + sdf.format(getNextWeekMonday(date)));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
輸出結果:
今天是2017-09-10
上週一2017-08-28
本週一2017-09-04
下週一2017-09-11
程式碼下載地址:http://download.csdn.net/download/zhaodecang/9971753