首先,LocalDate是一个immutable class(不可变类),
所以和String类一样,不需要new一个新的对象才可以使用,
LocalDate类用于设定日期的是of方法(重载),以下是其中的一个:
public static LocalDate of(int year, int month, int dayOfMonth)
设置年月日,好消息是这里的month是从1开始的。
下面是LocalDate类用于比较日期的until方法:
public Period until(ChronoLocalDate endDateExclusive)
方法返回的是一个Period类型的对象,Period代表的是形如“2年,3个月,4天”的一段时间间隔
public long until(Temporal endExclusive, TemporalUnit unit)
方法返回的是一个long类型的具体数值,long代表的是形如“2年”,“17个月”,“486天”的具体到某一时间单位的时间间隔
示例代码如下:
public static int getAge(String identType, String identNum, String birthDate) {
int age = 0;
LocalDate birthday;
if ("01".equals(identType) || "02".equals(identNum)) {
// 根据身份证获取出生日期
int year = Integer.parseInt(identNum.substring(6, 10));
int month = Integer.parseInt(identNum.substring(10, 12));
int day = Integer.parseInt(identNum.substring(12, 14));
birthday = LocalDate.of(year, month, day);
} else {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
birthday = LocalDate.parse(birthDate, dateTimeFormatter);
}
if (null != birthday) {
// 当前日期
LocalDate today = LocalDate.now();
age = (int) birthday.until(today, ChronoUnit.YEARS);
// age = (int) ChronoUnit.YEARS.between(birthday, today);
// Period period = Period.between(birthday, today);
// age = period.getYears();
}
return age;
}