If you cannot use java8, it is recommended to use the Calendar class. The code is as follows. add Just pass a negative value in the second parameter of the method.
Calendar now = Calendar.getInstance();
now.add(Calendar.DAY_OF_MONTH, -30);
String endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now.getTime());
System.out.println(endDate);
The java8 version can use the following method:
LocalDateTime now = LocalDateTime.now();
now = now.minus(30, ChronoUnit.DAYS);
System.out.println(now.toString());
public class Test {
public static void main(String[] args) {
Date endDate = new Date();
Date startDate = getDateBefore(new Date(),30);
}
private static Date getDateBefore(Date d, int day){
Calendar now =Calendar.getInstance();
now.setTime(d);
now.set(Calendar.DATE,now.get(Calendar.DATE)-day);
return now.getTime();
}
}
If you cannot use java8, it is recommended to use the Calendar class. The code is as follows.
add
Just pass a negative value in the second parameter of the method.The java8 version can use the following method:
As follows, the final format can be converted as needed:
startDate = nowDate - 30 * 24 * 60 * 60 * 1000
Just subtract thirty days of milliseconds from the current time.