如何使用 Java 中的日历计算从今天起的 30 天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12866879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to calculate 30 days back from today using Calendar in Java
提问by Shahar Galukman
I want to calculate the date 30 days back from today's date.
我想计算从今天的日期起 30 天后的日期。
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();
在上面你可以看到我正在使用 Calendar cal = Calendar.getInstance();
How do I calculate the date of 30 days before the extracted date?
如何计算提取日期前 30 天的日期?
Thanks for any help given.
感谢您提供的任何帮助。
回答by Jigar Joshi
Just use add()
method with -30
days
只用几天的add()
方法-30
calReturn.add(Calendar.DATE, -30);
回答by Amit Deshpande
You need to add -30
which will be subtraction.
您需要添加-30
这将是减法。
calReturn.add(Calendar.DATE, -30);
回答by Yogendra Singh
Use a negative numberin add()
method as -30
, which will work like date+(-30)
==> date-30
在方法 as 中使用负数,它会像==>一样工作add()
-30
date+(-30)
date-30