Date和String类型之间的转换,通过Calendar类求出年龄

通过使用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;

}



}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值