根據當前日期、天數,取得當前日期減去天數之前的日期
方法一:
SimpleDateFormat sdformat = new SimpleDateFormat("yyyy/MM/dd");
Date newDate=new Date();
String endDate = sdformat.format(newDate);//取得系統時間的當前日期,即結束時間
Date before7Day =getDate(endDate, 7);//當前日期-7,取得開始時間
String startDate = sdformat.format(before7Day);
public static Date getDate(String dateString , int beforeDays) throws ParseException{
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date inputDate = dateFormat.parse(dateString);
Calendar cal = Calendar.getInstance();
cal.setTime(inputDate);
int inputDayOfYear = cal.get(Calendar.DAY_OF_YEAR);
cal.set(Calendar.DAY_OF_YEAR , inputDayOfYear-beforeDays );
return cal.getTime();
}
方法二:
SimpleDateFormat sdformat = new SimpleDateFormat("yyyy/MM/dd");
Date newDate=new Date();
bean.setEndDate(sdformat.format(newDate));//取得系統時間的當前日期,即結束時間
bean.setStartDate(sdformat.format(addDate(newDate, -7)));//當前日期-7,取得開始時間
public static Date addDate(Date dt, int amount){
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.add(Calendar.DAY_OF_MONTH, amount);
return cal.getTime();
}