JAVA-java日期工具类
日期工具类
一、根据出生年月日获取到年龄
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;
}
}
## 三、ISO 8601日期(2025-04-15T09:01:20.649Z)UTC
try
{
// 定义 SimpleDateFormat 并设置格式和时区
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // 关键:指定 UTC 时区
// 解析字符串为 Date 对象
Date date = sdf.parse(str);
// 输出结果
System.out.println("Parsed Date: " + date); // 默认按本地时区显示
System.out.println("UTC Time: " + sdf.format(date)); // 格式化为 UTC 时间
}
catch (ParseException e)
{
throw new RuntimeException(e);
}
本文来自博客园,作者:skystrivegao,转载请注明原文链接:https://www.cnblogs.com/skystrive/p/18580823
整理不易,如果对您有所帮助 请点赞收藏,谢谢~