Java日期加減運算

1.用java.util.Calender來實現

 Calendar calendar=Calendar.getInstance();  
   calendar.setTime(new Date());
   System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//今天的日期
   calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);//讓日期加1  
   System.out.println(calendar.get(Calendar.DATE));//加1之後的日期Top

2.用java.text.SimpleDateFormat和java.util.Date來實現
          
   

 Date d=new Date();  
   SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");  
   System.out.println("今天的日期:"+df.format(d));  
   System.out.println("兩天前的日期:" + df.format(new Date(d.getTime() - 2 * 24 * 60 * 60 * 1000)));  
   System.out.println("三天後的日期:" + df.format(new Date(d.getTime() + 3 * 24 * 60 * 60 * 1000)));

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章