Java8使用LocalDate 获取日期间隔年、月、日,生日

1、代码

package com.myfutech.insure.service.api.util;
 
 
import org.apache.commons.lang3.time.DateUtils;
 
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
 
/**
 * @author liuxd
 * 生日计算公式
 * 周岁 = 现年份-出生年份(今年的生日已经过了)
 * 或者:周岁 = 现年份-出生年份-1(今年的生日还没过)
 * @version 1.0
 * @date 2020-01-13 14:23
 */
public class AgeUtil {
 
    
    public static int getYearsAge(Date birthDay) {
        LocalDate to = LocalDate.now();
        LocalDate from = date2LocalDate(birthDay);
        int age = (int) ChronoUnit.YEARS.between(from, to);
        return age;
    }
 
    public static int getMothsAge(Date birthDay) {
        LocalDate to = LocalDate.now();
        LocalDate from = date2LocalDate(birthDay);
        int age = (int) ChronoUnit.MONTHS.between(from, to);
        return age;
    }
 
    public static int getDaysAge(Date birthDay) {
        LocalDate to = LocalDate.now();
        LocalDate from = date2LocalDate(birthDay);
        int age = (int) ChronoUnit.DAYS.between(from, to);
        return age;
    }
 
 
    /**
     * Date转LocalDate
     *
     * @param date
     */
    public static LocalDate date2LocalDate(Date date) {
        if (null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }
 
 
    public static void main(String[] args) throws Exception {
        Date date = DateUtils.parseDate("2019-01-14", "yyyy-MM-dd");
        int yearsAge = getYearsAge(date);
        int monthsAge = getMothsAge(date);
        int daysAge = getDaysAge(date);
 
        System.out.println(yearsAge);
        System.out.println(monthsAge);
        System.out.println(daysAge);
 
    }
 
}

0评论