用户输入生日,输出用户到此时刻生存了多少天?

用户输入生日,输出用户到此时刻生存了多少天?

public class Demo1 {
    
    /**
     * @param args
     * @throws ParseException
     */
    public static void main(String[] args) throws ParseException {
        Scanner s = new Scanner(System.in);
        System.out.println("输入生日yyyy-MM-dd格式");
        //用户输入生日
        String birthStr =s.next();
        String birthRegex = "(19)+[\\d]{2}-([0][0-9]|[1][0-2])-([0-2][\\d]|[3][0-1])";
        if(birthStr.matches(birthRegex)){
            
            //获取用户输入的字符串格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //获取到的日期解析成Date类型 把String转换成Date
            Date birthDate = sdf.parse(birthStr);
            //创建date对象,获取当前时间
            Date CurrentDate = new Date();
            //最终结果
            long result = (CurrentDate.getTime() - birthDate.getTime())/1000/60/60/24;
            System.out.println("活了"+result+"天");
        }
        else{
            System.out.println("格式非法");
        }
    }
    
}
View Code

 

posted @ 2016-04-30 18:13  安仔80  阅读(281)  评论(0编辑  收藏  举报