import java.util.*; import java.text.*; class ChineseDate{ private Calendar aday; public ChineseDate(int year, int month,int day)throws MyDateException{ //this.aday= new Calendar();//不行,因为Calendar是抽象类 //this(); this.aday = Calendar.getInstance(); //※※※ this.set(year,month,day); } public ChineseDate(){ this.aday = Calendar.getInstance(); } public void set(int year, int month, int day)throws MyDateException{//抛异常 //进行业务逻辑的合法性处理 if(year<=0 || year>2500){ throw new MyDateException("年份错误,有效年份为:0~2500。"); } if(month<=0 || month>12){ throw new MyDateException("月份错误!"); } if(day<=0 || day>daysOfMonth(year,month) ){ throw new MyDateException("日期错误"); } this.aday.set(year,month-1,day); //※※※ } public static boolean isLeapYear( int year ){ boolean boo=year%400==0 || year%100!=0&&year%4==0; return boo; } public boolean isLeapYear(){ return this.isLeapYear(aday.get(Calendar.YEAR)); } public static int daysOfMonth(int year,int month){ switch(month){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: return isLeapYear(year)? 29:28; default: return 0; } } /* //※※※ public int daysOfMonth(){ return daysOfMonth(aday.get(Calendar.YEAR),aday.get(Calendar.MONTH)); } */ public String toString(){ return new SimpleDateFormat("yyyy年MM月dd日 EEEEE a hh 时 mm 分 ss 秒").format( new Date(aday.getTimeInMillis()) ); } public static void main(String args[]){ try{//接异常 ,异常处理 System.out.println( new ChineseDate(2015,1,23) ); }catch(MyDateException e){ System.out.println("aaaa----:"+e.toString() ); if(e.toString().equals("年份错误,有效年份为:0~2500。")){ System.out.println("发现年份出错的异常,进行相应处理...."); } if(e.toString().equals("月份错误!")){ System.out.println("发现月份出错的异常,进行相应处理...."); } if(e.toString().equals("日期错误")){ System.out.println("发现日期出错的异常,进行相应处理...."); } }catch(Exception e){ e.printStackTrace(); } System.out.println("我很好..."); } }
时间: 2024-11-08 08:07:11