本篇文章简单介绍一下关于时间类型方法的使用
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);
}
}