public class DateUtil {
/**
* 指定日期和日期间隔,返回间隔之前的日期
* @param specifiedDay
* @param interval
* @return
*/
public static String getSpecifiedDayAgo(String specifiedDay, int interval){
return getSpecifiedDay(specifiedDay, interval, "-");
}
/**
* 指定日期和日期间隔,返回间隔之前的日期
* @param specifiedDay
* @param interval
* @return
*/
public static String getSpecifiedDayAfter(String specifiedDay, int interval){
return getSpecifiedDay(specifiedDay, interval, "+");
}
private static String getSpecifiedDay(String specifiedDay, int interval, String func) {
Calendar c = Calendar.getInstance();
Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(specifiedDay);
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day=c.get(Calendar.DATE);
if("+".equals(func)) {
c.set(Calendar.DATE, day + interval);
} else if("-".equals(func)) {
c.set(Calendar.DATE, day - interval);
} else {
return null;
}
String dayAfter = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
return dayAfter;
}
public static void main(String[] args){
String d1 = getSpecifiedDayAfter("2017-01-11", 7);
String d2 = getSpecifiedDayAgo("2017-01-11", 7);
System.out.println(d1);
System.out.println(d2);
}
}
2017-01-18
2017-01-04