Java Calendar处理一些日期与星期的转换

时间:2022-01-31 18:06:00
  1. /** 
  2.     * 判断当前日期是星期几<br> 
  3.     * <br> 
  4.     * @param pTime 修要判断的时间<br> 
  5.     * @return dayForWeek 判断结果<br> 
  6.     * @Exception 发生异常<br> 
  7.     */  
  8. public static int dayForWeek(String pTime) throws Exception {  
  9.  format = new SimpleDateFormat("yyyy-MM-dd");  
  10.  Calendar c = Calendar.getInstance();  
  11.  c.setTime(format.parse(pTime));  
  12.  int dayForWeek = 0;  
  13.  if(c.get(Calendar.DAY_OF_WEEK) == 1){  
  14.   dayForWeek = 7;  
  15.  }else{  
  16.   dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;  
  17.  }  
  18.  return dayForWeek;  
  19. }  
  20. /**
      * 得到本周周一
      * 
      * @return yyyy-MM-dd
      */

     public static String getMondayOfThisWeek() {
      Calendar c = Calendar.getInstance();
      int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
      if (day_of_week == 0)
       day_of_week = 7;
      c.add(Calendar.DATE, -day_of_week + 1);
      return format.format(c.getTime());
     }

     

     /**
      * 得到本周周日
      * 
      * @return yyyy-MM-dd
      */

     public static String getSundayOfThisWeek() {
      Calendar c = Calendar.getInstance();
      int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
      if (day_of_week == 0)
       day_of_week = 7;
      c.add(Calendar.DATE, -day_of_week + 7);
      return format.format(c.getTime());
     }