java 给一个日期判断是星期几

最近在做给定一个日期,例如2013 1 1判断是星期几,看到网上代码都是用Calendar,我也测试了几个,感觉判断的不怎么准确,求大神指点一下,感激不尽啊

    /**
     * 判断当前日期是星期几<br>
     * <br>
     * @param pTime 修要判断的时间<br>
     * @return dayForWeek 判断结果<br>
     * @Exception 发生异常<br>
     */
 public static int dayForWeek(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;
 }

追问

请问一下调用dayForWeek()的时候pTime这个怎么传,我传了string抛异常啊

追答

按照格式来啊,比如:2013-02-13

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-01-05

我觉得可以参考这个:http://blog.csdn.net/a9529lty/article/details/3206942

 方法1:

   /** 
    * 判断当前日期是星期几<br> 
    * <br> 
    * @param pTime 修要判断的时间<br> 
    * @return dayForWeek 判断结果<br> 
    * @Exception 发生异常<br> 
    */  
public static int dayForWeek(String pTime) throws Exception {  
 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;  
}

方法2:

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);  
}

第2个回答  2019-05-08
public static String getWeekStr(Date date) {
   Calendar cal = Calendar.getInstance();
   if(date!=null)
      cal.setTime(date);
   int week  = cal.get(Calendar.DAY_OF_WEEK);
   switch (week) {
   case 1:
      return "星期日";
   case 2:
      return "星期一";
   case 3:
      return "星期二";
   case 4:
      return "星期三";
   case 5:
      return "星期四";
   case 6:
      return "星期五";
   case 7:
      return "星期六";
   }
   return "";
}

相似回答