A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© EDDY_Liang 中级黑马   /  2014-9-2 16:44  /  1074 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public static void main(String[] args) throws IOException{

  2. [code]public static void main(String[] args) throws IOException{
  3.                 //通过键盘如果日期
  4.                 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  5.                
  6.                 String buf = null;
  7.                 while((buf = br.readLine())!= null){
  8.                         //定义正则表达式
  9.                         String regex = "[0-9]{4}-(0[1-9]|1[0-2])-([0][1-9]|[1-2][0-9]|3[0-1])";
  10.                        
  11.                         if(!buf.matches(regex)){
  12.                                 System.out.println("日期不合法");
  13.                                 continue;
  14.                         }
  15.                         int year = Integer.parseInt(buf.substring(0, 4));
  16.                         int month = Integer.parseInt(buf.substring(5, 7));
  17.                         int day = Integer.parseInt(buf.substring(8, 10));
  18.                         System.out.println(year+"年:"+month+"月:"+day+"日");
  19.                         Calendar cal = Calendar.getInstance();
  20.                         cal.set(year, month, day);
  21.                         int weekNum = cal.get(Calendar.DAY_OF_WEEK);
  22.                         int months = cal.get(Calendar.MONTH);
  23.                         String week = getWeek(weekNum);
  24.                         System.out.println("星期数:"+weekNum);
  25.                         System.out.println(week);
  26.                         System.out.println(months+"月");
  27.                        
  28.                 }
  29.                
  30.        
  31.                
  32.         }

  33.         public static String getWeek(int weekNum) {
  34.                 String[] weeks = {"","星期日","星期一","星期二","星期三","星期四","星期五","星期六","星期日"};
  35.                                 return weeks[weekNum];
  36.                        
  37.         }

  38. }
复制代码


当我运行的时候输入:2014-09-02
打印的结果是:
2014年:9月:2日
星期数:5
星期四
9月
为什么星期数DAY_OF_WEEK 的值是5啊??
哪位大神帮忙看一下,谢谢啊

4 个回复

倒序浏览
  cal.set(year, month, day);这句代码出问题了,因为第一个月为0,不是1,所以第二个参数应该写成month-1,这样才是你要求的日期啊

评分

参与人数 1黑马币 +10 收起 理由
EDDY_Liang + 10

查看全部评分

回复 使用道具 举报
新新人类嘿嘿嘿 发表于 2014-9-2 18:17
cal.set(year, month, day);这句代码出问题了,因为第一个月为0,不是1,所以第二个参数应该写成month-1, ...

晕。。。。我懂了。。。我太不细心了
回复 使用道具 举报
牛逼,这么多代码
回复 使用道具 举报

不多把。。。你是刚学的吗
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马