年龄的计算

本篇文章简单介绍一下关于时间类型方法的使用

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class test1 {
    public static void main(String[]args) throws ParseException{


        String birth=("1996-06-29");
        //创建calendar实例
        Calendar cal=Calendar.getInstance();
        //获得当前时间
        Date now=new Date();
        //为Calendar实例设置当前时间
        cal.setTime(now);
        //获得cal对象的年份
        int nowyear = cal.get(Calendar.YEAR);

        //创建SimpleDateFormat时间格式
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        //解析生日
        Date birth1=sdf.parse(birth);
        //为Calendar实例设置生日时间
        cal.setTime(birth1);
        //获得cal对象的年份
        int birthyear=cal.get(Calendar.YEAR);
        //现在时间年份-生日年份
        int age=nowyear-birthyear;
        //输出年龄
        System.out.println(age);

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值