How to subtract X day from a Date object in Java?
@JigarJoshi it's the good answer, and of course also @Tim recommendation to use .joda-time.
I only want to add more possibilities to subtract days from a java.util.Date
.
Apache-commons
One possibility is to use apache-commons-lang. You can do it using DateUtils
as follows:
Date dateBefore30Days = DateUtils.addDays(new Date(),-30);
Of course add the commons-lang
dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang
it's a good choice. There is also convenient methods to addYears
,addMonths
,addWeeks
and so on, take a look at the api here.
Java 8
Another possibility is to take advantage of new LocalDate
from Java 8 using minusDays(long days)
method:
LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);
Java 8 and later
With Java 8's date time API change, Use LocalDate
LocalDate date = LocalDate.now().minusDays(300);
Similarly you can have
LocalDate date = someLocalDateInstance.minusDays(300);
Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
Java 7 and earlier
Use Calendar
's add()
method
Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();
Simply use this to get date before 300 days, replace 300 with your days:
Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();
Here,
DateTime
is org.joda.time.DateTime;
Date
is java.util.Date