Object的常用类Date经典案例--计算一个人出生天数,出生毫秒值

思路:1.获取当前时间对应的毫秒值
           2.获取自己出生日期对应的毫秒值
           3.两个时间相减(当前时间– 出生日期)
代码解答:

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

public class Demo03BirthdayDate {
    public static void main(String[] args) throws ParseException{
        //首先从键盘输入一个人的生日并提供格式
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入您的生日: 格式为yyyy-MM-dd");
        String str = sc.next();
        
        //将输入的生日按照以下格式解析为Date格式
        SimpleDateFormat daf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = daf.parse(str);
        long birth = date.getTime();    //求出出生时的时间毫秒值

        Date nowTime = new Date();
        long now = nowTime.getTime();   //求出现在的日期毫秒值

        long birthTime = now - birth;   //现在的日期毫秒值和出生当天的日期毫秒值的差就是出生的时间毫秒值
                                        //毫秒值换算公式  1000毫秒 == 1        System.out.println("您出生的天数为:"+birthTime/1000/60/60/24+"");//转换成天数
    }
}

猜你喜欢

转载自blog.csdn.net/snack_tc_dora/article/details/81053952