[英]Date Manipulation using Calendar class in Java
Please refer to the simple code below. 请参考下面的简单代码。 I want to deduct one month from current month and expecting value of February 2015 in output. 我想从当月扣除一个月,并期望在2015年2月的输出值。
Calendar today = Calendar.getInstance();
System.out.println(today.getTime().toString());
today.set(Calendar.MONTH, -1);
Date date = today.getTime();
System.out.println(date.toString());
The program output is as below. 程序输出如下。 I don't see the month February as expected, instead is shows Dec 2014 as month. 我没有看到预期的2月,而是将2014年12月显示为月。
Tue Mar 31 11:48:34 EDT 2015 2015年3月31日星期二11:48:34
Wed Dec 31 11:48:34 EST 2014 美国东部时间2014年12月31日星期三11:48:34
Thanks for your time and help. 感谢您的时间和帮助。
You're setting the month number to be -1, ie "December of the year before". 你设置的月份数为-1,即“前一年的12月。”。 You want to add -1 month: 您要添加 -1个月:
today.add(Calendar.MONTH, -1);
I'd strongly recommend using Joda Time or Java 8's java.time
package if you possibly can though - both are much nicer APIs than Date
/ Calendar
. 我强烈建议使用约达时间或Java 8的java.time
包,如果你可能可以,但-两者都好得多的API比Date
/ Calendar
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.