/** 第一种最老实的方法 */
public class BetweenDay {
public static void main(String[] args) {
between(2012,12,23); //0天
between(1988,7,9);//8933天
}
//1.求出当前时间距离1970年的毫秒数
//2.求出生日那天距离1970年的毫秒数
//两个做差
//?问题主要在如何根据历法获得long
public static void between(int year,int month,int day){
Calendar birth = new GregorianCalendar();
birth.set(year, month -1, day);
Date date = new Date(); //精髓在于long Date Calendar 三者之间的转换 向右是setTime() 向左转换用getTime()
date = birth.getTime();
long time = date.getTime();
//以上三句可以简写成一句 ,其实就是等量代换 long time = birth.getTime().getTime(); 效果是一样的
long betTime = System.currentTimeMillis() - time;
System.out.println("你活了:" + betTime/60/60/24/1000 + " 天");
}
}
/**第二种方法*/
public class CalcBirthTime {
public static void main(String[] args) {
CalcBirthTime();
}
//1.在控制台格式输入生日日期
//2.格式转换成日期
//3.控制台输入任意要查询的日期 并转换成日期格式
//4.将两个日期转换成长整形 做差 得到活了多少岁
public static void CalcBirthTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("请按照yyyy-MM-dd的日期格式输入你的生日:");
Scanner scanner = new Scanner(System.in);
String birth = scanner.nextLine();
System.out.println("请按照yyyy-MM-dd的日期格式输入你要查询的日期:");
String now = scanner.nextLine();
try {
Date date = sdf.parse(birth);
long birthTime = date.getTime();
Date dateNow = sdf.parse(now);
long checkTime = dateNow.getTime();
// long time = (checkTime - birthTime)/60/60/24/1000;
System.out.println("你活了:" + (checkTime - birthTime)/60/60/24/1000 + " 天");
} catch (ParseException e) {
e.printStackTrace();
}
}
}