安卓_关于时间的运算

 如何获得当前日期???

  

  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 is amount, 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 afterfield 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 than DAY_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:

    add in class  Calendar

    Parameters:

    field - the calendar field.

    amount - the amount of date or time to be added to the field.

    Throws:

    IllegalArgumentException - if field is ZONE_OFFSETDST_OFFSET, or unknown, or if any calendar fields have out-of-range values in non-lenient mode.

    See Also:

    Calendar.roll(int,int)Calendar.set(int,int)

         很长不想看????下面有精华版的...

    
           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()));
		   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

apple_51426592

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值