代码如下:
package tt;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
public class TestDate {
/* 三种时间格式 */
public static final String DATE_FORMAT = "yyyy-MM-dd";
public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DATETIME = "yyyyMMddHHmmss";
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Date date = sdf.parse("2016-07-04");
Date date2 = removeDays(date1, 7);
System.out.println(toString(date2, DATETIME_FORMAT));
}
/* 日期减天数 */
public static Date removeDays(Date oldDate, int n) {
Date newDate = null;
Calendar calOld = Calendar.getInstance();
calOld.setTime(oldDate);
int day = calOld.get(Calendar.DAY_OF_YEAR);
Calendar calNew = Calendar.getInstance();
calNew.setTime(oldDate);
calNew.set(Calendar.DAY_OF_YEAR, day - n);
newDate = calNew.getTime();
return newDate;
}
/* Date转string类型 */
public static String toString(Date date, String formatStr) {
if (null == date || StringUtils.isBlank(formatStr)) return "";
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
return sdf.format(date);
}
}