本地时间毫秒值-生日毫秒值 再格式化回来为什么会是1989年?

分别计算毫秒值相减

img


为什么格式化回来是这样?

img

使用LocalDate,计算出年份差,月份和日期


        String briStr = "1999-12-12";
        LocalDate parse = LocalDate.parse(briStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate now = LocalDate.now();
        int year = now.getYear() - parse.getYear();
        // 判断有没有过完生日
        if (now.getMonthValue() - parse.getMonthValue() < 0 ){
            year--;
        } else if (now.getMonthValue() - parse.getMonthValue() == 0 
                && now.getDayOfMonth() - now.getDayOfMonth() < 0) {
            year--;
        }
        System.out.println(year);

时间类的毫秒值是从1970.1.1 00:00:00开始算的,图中只算出活了多少毫秒,要计算年龄还要换算成多少年。

你把两个年份相减,然后重新格式化成一个年份的样子,是想做什么呢?
极限方式思考,你把今天减去昨天,那么就是24小时x3600秒x1000毫秒
你把它变成年月日时分秒,你猜会是个什么玩意?
所以你的思路整个就错了。不要把两个年份转毫秒之后相减,那样毫无意义。
你应该两个时间类型直接相减,相减后的类型是TimeSpan,然后分别取年月日时分秒。

时间类型如果转换成毫秒是从1970.1.1 00:00:00开始计算,也就是这个时间点对应的值是0,所以你的相减逻辑上是错误的。