1. 程式人生 > >java Date 加上10天 得到某日期是星期幾

java Date 加上10天 得到某日期是星期幾

//加10天

SimpleDateFormat format = new   SimpleDateFormat(“yyyy-MM-dd”); 

   Date dd = new Date();

   Calendar calendar = Calendar.getInstance();

   calendar.setTime(dd);

   calendar.add(Calendar.DATE,10); 

   String T1 = format.format(calendar.getTime() ) ;

   //加5天

   calendar.setTime(dd);

   calendar.add(Calendar.DATE, 5); 

   String T2 = format.format(calendar.getTime() ) ;

public static void main(String[] a) throws ParseException{
  String dayDate = "2012-01-01";
  String dayWeek = ""; //當前日期星期幾
  String beforeWeek = ""; //前一天 星期幾
  String afterWeek = ""; //後一天 星期幾
  
  // 得到當前日期是星期幾
  String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
  
  String beforeDay = ""; //前一天
  //根據當前日期得到前一天的日期
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  Date dd = format.parse(dayDate);
  Calendar calendar1 = Calendar.getInstance();
  calendar1.setTime(dd);
  int w = calendar1.get(Calendar.DAY_OF_WEEK) - 1;
  if(w < 0) w = 0;
  dayWeek = weekDays[w];
  calendar1.add(Calendar.DATE,-1);
  w = calendar1.get(Calendar.DAY_OF_WEEK) - 1;
  if(w < 0) w = 0;
  beforeWeek = weekDays[w];
  beforeDay = format.format(calendar1.getTime()) ;
  
  String afterDay = ""; //後一天
  //根據當前日期得到後一天的日期
  dd = format.parse(dayDate);
  Calendar calendar2 = Calendar.getInstance();
  calendar2.setTime(dd);
  calendar2.add(Calendar.DATE,1);
  w = calendar2.get(Calendar.DAY_OF_WEEK) - 1;
  if(w < 0) w = 0;
  afterWeek = weekDays[w];
  afterDay = format.format(calendar2.getTime()) ;
  
  System.out.println(dayWeek);
  System.out.println(beforeDay);
  System.out.println(beforeWeek);
  System.out.println(afterDay);
  System.out.println(afterWeek);
 }