Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate 30 days back from today using Calendar in Java

Tags:

java

calendar

I want to calculate the date 30 days back from today's date.

public void dateSetup(){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd ");
        Calendar cal = Calendar.getInstance();
        Calendar calReturn = Calendar.getInstance();
        jDate_timeOfExpectedReturn1.setText(dateFormat.format(cal.getTime()));
        calReturn.add(Calendar.DATE, 30);
        jDate_timeOfLoan1.setText(dateFormat.format(calReturn.getTime()));
    }

Above you can see that I'm extracting today date using Calendar cal = Calendar.getInstance();

How do I calculate the date of 30 days before the extracted date?

Thanks for any help given.

like image 655
Shahar Galukman Avatar asked Oct 12 '12 20:10

Shahar Galukman


3 Answers

Just use add() method with -30 days

 calReturn.add(Calendar.DATE, -30);
like image 178
jmj Avatar answered Oct 20 '22 17:10

jmj


You need to add -30 which will be subtraction.

calReturn.add(Calendar.DATE, -30);
like image 36
Amit Deshpande Avatar answered Oct 20 '22 18:10

Amit Deshpande


Use a negative number in add() method as -30, which will work like date+(-30) ==> date-30

like image 26
Yogendra Singh Avatar answered Oct 20 '22 17:10

Yogendra Singh