简体   繁体   中英

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

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.

只需使用add()方法-30

 calReturn.add(Calendar.DATE, -30);

你需要添加-30 ,这将是减法。

calReturn.add(Calendar.DATE, -30);

add()方法中使用负数作为-30 ,这将像date+(-30) ==> date-30

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM