tl;博士
Duration.between(
LocalTime.of( 12 , 5 , 0 ) ,
LocalTime.of( 12 , 7 , 0 )
).toString()
PT2M
如果反对我强烈建议使用Duration,您坚持使用模棱两可/令人困惑的时间格式:
LocalTime.MIN.plus(
Duration.between(
LocalTime.of( 12 , 5 , 0 ) ,
LocalTime.of( 12 , 7 , 0 )
)
).toString();
00:02
要强制所有三个分量(小时、分钟、秒),请使用预定义的DateTimeFormatter.ISO_LOCAL_TIME。
LocalTime.MIN.plus(
Duration.between(
LocalTime.of( 12 , 5 , 0 ) ,
LocalTime.of( 12 , 7 , 0 )
)
).format( DateTimeFormatter.ISO_LOCAL_TIME )
00:02:00
见live code in IdeOne.com。
时刻 != 时间跨度
不要滥用日期时间类(例如 java.util.Date)来存储经过的时间。这样的类代表一个时刻,而不是一个时间跨度。
避免使用旧的日期时间类
不要使用麻烦的旧日期时间类,例如java.util.Date。这些现在被 java.time 类所取代。
Instant
Instant 类代表UTC 中时间轴上的一个时刻,分辨率为nanoseconds。
获取当前时刻。
Instant now = Instant.now();
稍后模拟。
Instant future = now.plus( Duration.ofMinutes( 5 ) );
Duration
使用Duration 或Period 对象捕获经过的时间。每一个都代表一个时间跨度,第一个处理天-小时-分钟-秒,第二个处理年-月-日。
Duration duration = Duration.between( now , future );
字符串格式
要将持续时间值显示为字符串,请不要使用时间格式,因为这样会模棱两可。而是使用标准ISO 8601 format for durations。这种格式PnYnMnDTnHnMnS 以P 标记开头。中间的T 将年-月-日部分与小时-分钟-秒部分分开。例如,两个半小时是PT2H30M。我们这里五分钟的例子是PT5M。
String output = duration.toString(); // PT5M
LocalTime
如果您确实有一个实际的时间并希望使用填充零进行格式化,请使用默认格式 LocalTime::toString。
LocalTime.now( ZoneId.of( "America/Montreal" ) ).toString(); // 02:03:04.789Z
另一个例子。同样,我不建议以这种方式滥用LocalTime。 (相反,坚持使用Duration 等待已用时间。)
LocalTime start = LocalTime.now( ZoneId.of( "America/Montreal" ) );
LocalTime stop = start.plusMinutes( 7 );
Duration d = Duration.between( start , stop );
LocalTime result = LocalTime.MIN.plus( d ); // I do *not* recommend abusing `LocalTime` this way. Use `Duration` instead for elapsed time.
DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_TIME ;
String output = result.format( f );
System.out.println( "output: " + output );
输出:00:07:00
见live code in IdeOne.com。
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。