yetAnotherSE yetAnotherSE - 6 months ago 23
Java Question

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

I want to do something like:

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


How to do it?

Answer

Use Calendar's add() method

Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();