public class GetDay {
public static void main(String[] args) {
System.out.println("请输入公历生日日期(格式:1993-07-19):");
Scanner sc = new Scanner(System.in);
String str = sc.next();
Date birthday = getBirthdayDate(str);
if (birthday != null) {
long days = getDays(birthday);
System.out.println("迄今来到这个世界共 " + days + " 天!");
} else {
System.out.println("不合法的日期格式!");
}
}
// 将键盘输入的 String类型的日期转换为 Date 类型的日期
public static Date getBirthdayDate(String str) {
Date date = null;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
return df.parse(str);
} catch (Exception e) {
date = null;
}
return date;
}
// 计算现今距出生日期过去的天数
public static long getDays(Date birthday) {
Date now = new Date();
long time = now.getTime() - birthday.getTime();
long days = time / (24 * 60 * 60 * 1000);
return days;
}
}