日期和时间类别
LocalTime
LocalTime类与其他名称带有Local
前缀的其他类相似,但只能及时处理。此类对于表示基于人的时间(例如电影时间或本地 Library 的开放和关闭时间)很有用。它也可以用于创建数字时钟,如以下示例所示:
LocalTime thisSec;
for (;;) {
thisSec = LocalTime.now();
// implementation of display code is left to the reader
display(thisSec.getHour(), thisSec.getMinute(), thisSec.getSecond());
}
LocalTime
类不存储timezone或夏令时信息。
LocalDateTime
处理日期和时间(不带timezone)的类是LocalDateTime,这是 Date-Time API 的核心类之一。此类用于表示日期(月-日-年)和时间(时-分-秒-纳秒),并且实际上是LocalDate
和LocalTime
的组合。此类可以用来代表特定的事件,例如下午 1:10 开始的美国杯挑战赛系列中的路易威登杯决赛的第一场 match。请注意,这表示 2013 年 8 月 17 日下午 1 点 10 分。在当地时间。要包含timezone,您必须使用ZonedDateTime
或OffsetDateTime
,如timezone和offset类中所述。
除了每个基于时间的类都提供的now
方法之外,LocalDateTime
类还具有创建LocalDateTime
实例的各种of
方法(或带有of
前缀的方法)。有一个from
方法将实例从另一种时间格式转换为LocalDateTime
实例。也有添加或减去小时,分钟,天,周和月的方法。以下示例显示了其中一些方法。日期时间表达式以粗体显示:
System.out.printf("now: %s%n", LocalDateTime.now());
System.out.printf("Apr 15, 1994 @ 11:30am: %s%n",
LocalDateTime.of(1994, Month.APRIL, 15, 11, 30));
System.out.printf("now (from Instant): %s%n",
LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()));
System.out.printf("6 months from now: %s%n",
LocalDateTime.now().plusMonths(6));
System.out.printf("6 months ago: %s%n",
LocalDateTime.now().minusMonths(6));
此代码产生的输出将类似于以下内容:
now: 2013-07-24T17:13:59.985
Apr 15, 1994 @ 11:30am: 1994-04-15T11:30
now (from Instant): 2013-07-24T17:14:00.479
6 months from now: 2014-01-24T17:14:00.480
6 months ago: 2013-01-24T17:14:00.481