How to reduce one month from current date and stored in date variable using java?
Use Calendar:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
Date result = cal.getTime();
Starting from Java 8, the suggested way is to use the Date-Time API rather than Calendar
.
If you want a Date
object to be returned:
Date date = Date.from(ZonedDateTime.now().minusMonths(1).toInstant());
If you don't need exactly a Date
object, you can use the classes directly, provided by the package, even to get dates in other time-zones:
ZonedDateTime dateInUTC = ZonedDateTime.now(ZoneId.of("Pacific/Auckland")).minusMonths(1);
Calendar calNow = Calendar.getInstance()
// adding -1 month
calNow.add(Calendar.MONTH, -1);
// fetching updated time
Date dateBeforeAMonth = calNow.getTime();