java根据日期返回星期几数字

警告:下面这种方法,出现了使用期间突然挂掉,内部不知是何变化,返回的数字全变了,所以在此提醒下,请不要使用

public  static  int  dayForWeek(String pTime) throws  Throwable {  
          
        SimpleDateFormat format = new  SimpleDateFormat("yyyy-MM-dd" );  
          
        Date tmpDate = format.parse(pTime);  
          
        Calendar cal = new  GregorianCalendar();  
          
        cal.set(tmpDate.getYear(), tmpDate.getMonth(), tmpDate.getDay());  
          
        return  cal.get(Calendar.DAY_OF_WEEK);  
    }  

下面这种方法,是最完善的

public  static  int  dayForWeeks(String pTime) throws  Exception {  
            SimpleDateFormat format = new  SimpleDateFormat("yyyy-MM-dd" );  
             Calendar c = Calendar.getInstance();  
             c.setTime(format.parse(pTime));  
             int  dayForWeek = 0 ;  
             if (c.get(Calendar.DAY_OF_WEEK) == 1 ){  
              dayForWeek = 7 ;  
             }else {  
              dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1 ;  
             }  
             return  dayForWeek;  
            }  

 

posted @ 2017-09-22 10:47  烟雨观春柳  阅读(839)  评论(0)    收藏  举报