Date d = Date.from(LocalDate.now().minusMonths(3).atStartOfDay(ZoneId.systemDefault()).toInstant());
The LocalDate class has a lot of methods to help you make easy computations about dates like the above,
// Add 2 months
Date d = Date.from(LocalDate.now().plusMonths(2).atStartOfDay(ZoneId.systemDefault()).toInstant());
// Add 5 days
Date d = Date.from(LocalDate.now().plusDays(5).atStartOfDay(ZoneId.systemDefault()).toInstant());
// Minus 1 day and 1 year
Date d = Date.from(LocalDate.now().minusYears(1).minusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
In order to compute time you can use the LocalDateTime class,
// Minus 1 year, minus 1 days, plus 1 hour
Date d = Date.from(LocalDateTime.now().minusYears(1).minusDays(1).plusHours(1).toLocalDate().atStartOfDay(ZoneId.systemDefault()).toInstant());
Here's the plain JDK version, it needs the Calendar class as a helper:
Date referenceDate = new Date();
Calendar c = Calendar.getInstance();
c.setTime(referenceDate);
c.add(Calendar.MONTH, -3);
return c.getTime();
But you should seriously consider using the Joda library, because of various shortcomings of the Date and Calendar classes. With Joda you can do the following:
new DateTime().minusMonths(3).toDate();
Or if you want to subtract from a given date instead of the current:
new DateTime(referenceDate).minusMonths(3).toDate();
Update for Java 8: With Java 8 you can also use the new JSR 310 API (which is inspired by Joda):
I always recommend Joda for this sort of stuff. It has a much nicer API, and doesn't suffer from threading issues that the standard Java date/time has (e.g. issues with SimpleDateFormat, or general mutability).
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(startDate);
String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
LocalDate today = LocalDate.parse(formattedDate);
String endDate=today.minusMonths(3).toString();
Using Java 8 you can do it like this,
The
LocalDate
class has a lot of methods to help you make easy computations about dates like the above,In order to compute time you can use the
LocalDateTime
class,Here's the plain JDK version, it needs the
Calendar
class as a helper:But you should seriously consider using the Joda library, because of various shortcomings of the
Date
andCalendar
classes. With Joda you can do the following:Or if you want to subtract from a given date instead of the current:
Update for Java 8: With Java 8 you can also use the new JSR 310 API (which is inspired by Joda):
Set your date using
setTime
method.I always recommend Joda for this sort of stuff. It has a much nicer API, and doesn't suffer from threading issues that the standard Java date/time has (e.g. issues with
SimpleDateFormat
, or general mutability).e.g.
String startDate="15/10/1987";