首先让我们明确时间 24:00 是有效的 ISO-8601 时间。来自 ISO-8601 的引用:
4.2 Time of day
4.2.1 General
This International Standard is based on the 24-hour timekeeping System
that is now in common use. In expressions of time of day
hour is represented by two digits from [00] to [24]. The representation
of the hour by [24] is only allowed to indicate the end of a calendar
day, see 4.2.3.
Java 本身不支持 24:00,除非您使用 SimpleDateFormat 的宽松解析模式。但是即使那样,支持也不可用,因为如果您询问结果(java.util.Date 的实例),您会得到零,正如您已经观察到的那样。类似的想法也适用于java.util.GregorianCalendar。解析后,无法确定输入是否为 24:00(不知道原始输入是什么)。
Java-8 也没有真正支持这个特殊的时刻。您可以在这里做的最好的事情是使用parseExcessDays() 应用于DateTimeFormatter 的原始解析数据。您可以使用这样的解决方法:
String input = "24:00:00";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
TemporalAccessor raw = dtf.parse(input);
int hour = raw.query(LocalTime::from).getHour();
Period period = raw.query(DateTimeFormatter.parsedExcessDays());
if (period.equals(Period.ofDays(1))) {
hour = 24;
}
System.out.println("iso-hour=" + hour); // output: iso-hour=24
流行的第 3 方库 Joda-Time 不支持 24:00。情况类似于SimpleDateFormat。
我知道的唯一具有内置支持的库是我自己编写的Time4J。完全支持仅限于PlainTime(类似于LocalTime 的挂件),不适用于完整的日期时间表示(如果它是矛盾的,包含24:00 的时间戳将自动归一化为第二天的00:00 ):
PlainTime time = Iso8601Format.EXTENDED_WALL_TIME.parse("24:00:00");
System.out.println(time.get(PlainTime.ISO_HOUR)); // 24
请注意,PlainTime 类的状态空间略微扩展,以便它可以保存这个特殊的 ISO 时间值。因此,像这样的直接编程访问是可能的:
PlainTime time24 = PlainTime.midnightAtEndOfDay(); // or: PlainTime.of(24, 0);
System.out.println(time24); // T24