日期工具類
一、根據出生年月日獲取到年齡
點選檢視程式碼
public static int getAgeByBirth(String birthDateString) {
int age = 0;
try {
DateTimeFormatter birthDateFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
// 解析出生日期字串為LocalDateTime,然後轉換為LocalDate以忽略時間部分
LocalDateTime birthDateTime = LocalDateTime.parse(birthDateString, birthDateFormatter);
LocalDate birthDate = birthDateTime.toLocalDate();
// 獲取當前日期
LocalDate currentDate = LocalDate.now();
// 計算年齡(年份差,如果當前日期早於當年的生日則減一)
age = currentDate.getYear() - birthDate.getYear();
if (currentDate.isBefore(birthDate.withYear(currentDate.getYear()))) {
age--;
}
} catch (Exception e) {
e.printStackTrace();
}
return age;
}
二、時間戳型別字串轉換成Date型別
點選檢視程式碼
public static Date getDateTime(String timeStampString) {
Date date = null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
// 將字串解析為Date物件
date = dateFormat.parse(timeStampString);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
}