1. 程式人生 > >Java獲取三個月的時間

Java獲取三個月的時間

Date dNow = new Date();   //當前時間  
      Date dBefore = new Date();  
      Calendar calendar = Calendar.getInstance(); //得到日曆  
      calendar.setTime(dNow);//把當前時間賦給日曆  
      calendar.add(Calendar.MONTH, -3);  //設定為前3月  
      dBefore = calendar.getTime();   //得到前3月的時間  
      SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //設定時間格式  
      String defaultStartDate = sdf.format(dBefore);    //格式化前3月的時間  
      String defaultEndDate = sdf.format(dNow); //格式化當前時間  
      System.out.println("三個月之前時間======="+defaultStartDate);  
      System.out.println("當前時間==========="+defaultEndDate); 
      
      Date createdDate = new Date();
      Date endDate = new Date();
      Date beforeNowTenDay = new Date(endDate.getTime() - 1000 * 60 * 60 * 24 * 30);
      Date startDate = createdDate.before(beforeNowTenDay) ? beforeNowTenDay : createdDate;
      Date nowDate = new Date();
      Date afterStartDateTenDay = new Date(startDate.getTime() + 1000 * 60 * 60 * 24 * 30);
      endDate = nowDate.before(afterStartDateTenDay) ? nowDate : afterStartDateTenDay;
      System.out.println("beforeNowTenDay===="+beforeNowTenDay); 
      System.out.println("afterStartDateTenDay===="+afterStartDateTenDay);