如何获得当前日期???
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); GregorianCalendar gc=new GregorianCalendar(); gc.setTime(new Date()); System.out.println("今天的日期:"+df.format(gc.getTime()));
OK.成功获取的今天的日期..那如何在这个基础上..修改下日期..例如增加多一天.减少多一个月之类的呢??
那肯定是在 gc 这个变量上做手脚啦..人家叫GregorianCalendar..啊.
为了凑字数..我把关于关于时间操作的某个函数的一堆解释废话贴上来
void java.util. GregorianCalendar.add( int field, int amount)
-
add
public void add(int field, int amout)
Adds the specified (signed) amount of time to the given calendar field, based on the calendar's rules.Add rule 1. The value of
field
after the call minus the value offield
before the call isamount
, modulo any overflow that has occurred infield
. Overflow occurs when a field value exceeds its range and, as a result, the next larger field is incremented or decremented and the field value is adjusted back into its range.Add rule 2. If a smaller field is expected to be invariant, but it is impossible for it to be equal to its prior value because of changes in its minimum or maximum after
field
is changed, then its value is adjusted to be as close as possible to its expected value. A smaller field represents a smaller unit of time.HOUR
is a smaller field thanDAY_OF_MONTH
. No adjustment is made to smaller fields that are not expected to be invariant. The calendar system determines what fields are expected to be invariant.Specified by:
Parameters:
field
- the calendar field.amount
- the amount of date or time to be added to the field.Throws:
IllegalArgumentException
- iffield
isZONE_OFFSET
,DST_OFFSET
, or unknown, or if any calendar fields have out-of-range values in non-lenient mode.See Also:
很长不想看????下面有精华版的...
gc.add(5,-4)//表示日期减4 gc.add(5,8)//表示日期加8 // gc.add(field,value); // value为正则往后,为负则往前 // field取1加1年,取2加半年,取3加一季度, // 取4加一周.取5加一天....
下面这段代码可以直接运行.复制,然后测试下.
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); GregorianCalendar gc=new GregorianCalendar(); gc.setTime(new Date()); gc.add(5,-1); System.out.println("昨天的日期:"+df.format(gc.getTime()));