通过使用SimpleDateFormat这个类中的format方法和parse方法将Date类型和String类型之间的转化
1.将Date类型装换为String类型用parse的方法
父类
public Person{
Date brithday;
Person(){
}
}
public Student extends Person{
String name;
static SimpleDateFormat bir=new SimpleDateFormat("yyyy-yy-yy");//指定之家想要的日期格式
Student(String brithday,String name){
super(bir.parse(brithday));//实现转换
this.name=name;
}
}
2.将String转换为Date类型用format方法
public Student{
String brithday;
Stirng name;
static SimpleDateFormat bir=new SimpleDateFormat("yyyy-yy-yy");//指定之家想要的日期格式
Student(Date brithday,String name){
this.brithday=bir.format(brithday);//实现转换
this.name=name;
}
}
如何通过生日来求年龄,使用Calendar类。
public int getAge(){
Calendar cal=Calendar.getInstance();//获得当前的时间
if(cal.befor(birthday)){
throw new IllegalArgumentException("The brithday is befor now");
int yearnow=cal.get(Calendar.YEAR);//获得当前的年份
int monthnow=cal.get(Calendar.MONTH)+1;
int dayofmonthnow=cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(brithday);//将以Date类型输入的生日分割
int yearbrithday=cal.get(Calendar.YEAR);
int monthbrithday=cal.get(Calendar.MONTH)+1;
int dayofmonthbrithday=cal.get(Calendar.DAY_OF_MONTH);
int age=yearbrithday-yearnow;
return age;
}
}