一. 程序思路
1.输入字符串出生日期,必须使用指定模式,例如:1993-12-23
2.将字符串类型的出生日期解析为Date对象类型
3.获取当前日期
4.计算差值
5.将单位毫秒转化为天
二. 代码实现
Main类
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws ParseException {
//根据输入的字符串计算一个人出生了多少天
//1.输入字符串出生日期,必须使用指定模式,例如:1993-12-23
Scanner scanner = new Scanner(System.in);
String birthday = scanner.next();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); //"yyyy-MM-dd"为模式
//2.将字符串类型的出生日期解析为Date对象类型
Date date = simpleDateFormat.parse(birthday);
//3.获取当前日期
Date currentDate = new Date();
//4.计算差值,difference为当前日期到出生日期的毫秒差值
long difference = currentDate.getTime() - date.getTime();
//5.将单位毫秒转化为天
int days = (int) (difference / (24 * 60 * 60 * 1000));
System.out.println("出生了" + days + "天");
}
}
三. 运行截图