我的日期字符串为“1/10/24 7:00 PM”(2024 年 1 月 10 日)。如何使用
SimpleDateFormat
解析它?
String date_time = "1/10/24 7:00 PM";
Instant answer;
try {
answer = Instant.parse(date_time);
} catch(DateTimeParseException ex) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
answer = simpleDateFormat.parse(date_time).toInstant();
System.out.println(answer);
}
我的日期字符串为“1/10/24 7:00 PM”(2024 年 1 月 10 日)。如何 使用 SimpleDateFormat 解析它?
java.util
日期时间 API 及其相应的解析/格式化类型 SimpleDateFormat
已过时且容易出错。 2014 年 3 月,现代日期时间 API 取代了旧版日期时间 API。从那时起,强烈建议切换到现代日期时间 API java.time
。
给定的日期时间字符串没有时区信息;因此,将其解析为
LocalDateTime
,然后应用系统默认时区将其转换为 ZonedDateTime
。最后,将 ZonedDateTime
转换为 Instant
。
演示:
public class Main {
public static void main(String[] args) {
String strDateTime = "1/10/24 7:00 PM";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/uu h:mm a", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf);
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
Instant output = zdt.toInstant();
System.out.println(output);
}
}
输出:
2024-01-10T19:00:00Z
Instant#parse
的字符串使用 DateTimeFormatter.ISO_INSTANT
,例如Instant.parse("2011-12-03T10:15:30Z")
。
了解现代日期时间 API