How to subtract X day from a Date object in Java?

yetAnotherSE picture yetAnotherSE · Aug 9, 2012 · Viewed 325k times · Source

I want to do something like:

Date date = new Date(); // current date
date = date - 300; // substract 300 days from current date and I want to use this "date"

How to do it?

Answer

Jigar Joshi picture Jigar Joshi · Aug 9, 2012

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();