tl;博士
将您过时的java.util.Date 对象转换为它们的替代对象java.time.Instant。然后将经过的时间计算为Duration。
Duration d =
Duration.between( // Calculate the span of time between two moments as a number of hours, minutes, and seconds.
myJavaUtilDate.toInstant() , // Convert legacy class to modern class by calling new method added to the old class.
Instant.now() // Capture the current moment in UTC. About two and a half hours later in this example.
)
;
d.toString(): PT2H34M56S
d.toMinutes(): 154
d.toMinutesPart(): 34
ISO 8601 格式:PnYnMnDTnHnMnS
明智的标准ISO 8601 将时间跨度的简明文本表示定义为年、月、日、小时等。标准将这样的跨度称为duration。格式为PnYnMnDTnHnMnS,其中P 表示“期间”,T 将日期部分与时间部分分开,中间是数字后跟一个字母。
例子:
-
P3Y6M4DT12H30M5S
三年六个月四天十二小时三十分钟五秒
-
PT4H30M
四个半小时
java.time
Java 8 中内置的 java.time 框架取代了麻烦的旧 java.util.Date/java.util.Calendar 类。新类的灵感来自非常成功的Joda-Time 框架,该框架旨在作为其继任者,在概念上相似但经过重新架构。由JSR 310 定义。由ThreeTen-Extra 项目扩展。请参阅Tutorial。
时刻
Instant 类代表UTC 中时间轴上的时刻,分辨率为nanoseconds(最多九 (9) 位小数)。
Instant instant = Instant.now() ; // Capture current moment in UTC.
最好避免使用遗留类,例如Date/Calendar。但是,如果您必须与尚未更新为 java.time 的旧代码进行互操作,请来回转换。调用添加到旧类的新转换方法。如需从java.util.Date 移动到Instant,请致电Date::toInstant。
Instant instant = myJavaUtilDate.toInstant() ; // Convert from legacy `java.util.Date` class to modern `java.time.Instant` class.
时间跨度
java.time 类将这种将时间跨度表示为年、月、日、小时、分钟、秒的想法分成两半:
这是一个例子。
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now ( zoneId );
ZonedDateTime future = now.plusMinutes ( 63 );
Duration duration = Duration.between ( now , future );
转储到控制台。
Period 和 Duration 都使用 ISO 8601 标准来生成其值的字符串表示形式。
System.out.println ( "now: " + now + " to future: " + now + " = " + duration );
现在:2015-11-26T00:46:48.016-05:00[美国/蒙特利尔] 到未来:2015-11-26T00:46:48.016-05:00[美国/蒙特利尔] = PT1H3M
Java 9 向 Duration 添加了方法来获取天部分、小时部分、分钟部分和秒部分。
您可以获得整个 Duration 中的总天数或小时数或分钟数或秒数或毫秒数或纳秒数。
long totalHours = duration.toHours();
在 Java 9 中,Duration class gets new methods 用于返回天、小时、分钟、秒、毫秒/纳秒的各个部分。调用to…Part 方法:toDaysPart()、toHoursPart() 等。
ChronoUnit
如果您只关心更简单的较大时间粒度,例如“经过的天数”,请使用 ChronoUnit 枚举。
long daysElapsed = ChronoUnit.DAYS.between( earlier , later );
另一个例子。
Instant now = Instant.now();
Instant later = now.plus( Duration.ofHours( 2 ) );
…
long minutesElapsed = ChronoUnit.MINUTES.between( now , later );
120
关于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。
乔达时间
更新:Joda-Time 项目现在位于maintenance mode,团队建议迁移到java.time 类。我保留这部分完整的历史记录。
Joda-Time 库默认使用 ISO 8601。它的Period 类解析并生成这些 PnYnMnDTnHnMnS 字符串。
DateTime now = DateTime.now(); // Caveat: Ignoring the important issue of time zones.
Period period = new Period( now, now.plusHours( 4 ).plusMinutes( 30));
System.out.println( "period: " + period );
渲染:
period: PT4H30M