用Calendar类,有很完善的日期方法,可以加减。
解决方案 »
- 各位大哥大姐,帮忙看下这个,为什么不能运行?
- 用JBuilder2005 怎么将Frame上面的X和放大缩小去掉啊!!
- 分不多,半夜请教,Set接口中重写hashCode()会提高性能,能不能举个例子
- 迷茫中的初学者
- 工作中用不到的Java基础用经常复习吗???
- 在类里定义一个成员变量 private Demo d =new Demo() 和private Demo=null有啥区别啊
- 我急呀!请问作类型转换问题???
- jmf到底怎么用,我好迷惘阿,神,阿救救我把
- 看下有什么结果
- 在JBuilder5下调试显示图片程序出现问题,请各位大狭帮忙解决!谢谢!!
- 如何在java applet里读本地的文件(我是从delphi大富翁来得,听说这里也不错,事实怎么样?)
- 免费网络技术讲座现在开始报名
add() and roll() are used to add or substract values to a Calendar object.
You specify which Calendar field is to be affected by the operation (Calendar.YEAR, Calendar.MONTH, Calendar.DATE). add() adds or substracts values to the specified Calendar field, the next larger field is modified when the result makes the Calendar "rolls over". String DATE_FORMAT = "yyyy-MM-dd";
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance();
c1.set(1999, 0 , 20); // 1999 jan 20
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.DATE,20);
System.out.println("Date + 20 days is : " + sdf.format(c1.getTime())); To substract, simply use a negative argument.
roll() does the same thing except you specify if you want to roll up (add 1) or roll down (substract 1) to the specified Calendar field. The operation only affects the specified field while add() adjusts other Calendar fields. See the following example, roll() makes january rolls to december in the same year while add() substract the YEAR field for the correct result. String DATE_FORMAT = "yyyy-MM-dd";
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance();
// roll down the month
c1.set(1999, 0 , 20); // 1999 jan 20
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.roll(Calendar.MONTH, false); // roll down, substract 1 month
System.out.println("Date roll down 1 month : " + sdf.format(c1.getTime())); // 1999 jan 20c1.set(1999, 0 , 20); // 1999 jan 20
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.MONTH, -1); // substract 1 month
System.out.println("Date minus 1 month : " + sdf.format(c1.getTime())); // 1998 dec 20