日期和时间
LocalTime 类
The LocalTime
类类似于其他以 Local
为前缀的类,但只处理时间。此类对于表示基于人类的时间,例如电影时间或当地图书馆的开放和关闭时间很有用。它也可以用于创建数字时钟,如以下示例所示
LocalTime thisSec;
for (;;) {
thisSec = LocalTime.now();
// implementation of display code is left to the reader
display(thisSec.getHour(), thisSec.getMinute(), thisSec.getSecond());
}
The LocalTime
类不存储时区或夏令时信息。
LocalDateTime 类
处理日期和时间(不含时区)的类是 LocalDateTime
,它是日期时间 API 的核心类之一。此类用于表示日期(月-日-年)以及时间(时-分-秒-纳秒),实际上是 LocalDate
和 LocalTime
的组合。此类可用于表示特定事件,例如美洲杯挑战赛系列中路易威登杯决赛的第一场比赛,该比赛于 2013 年 8 月 17 日下午 1:10 开始。请注意,这意味着当地时间下午 1:10。要包含时区,您必须使用 ZonedDateTime
或 OffsetDateTime
,如 时区和偏移量类 中所述。
除了每个基于时间的类都提供的 now()
方法外,LocalDateTime
类还具有各种 of()
方法(或以 of
为前缀的方法),这些方法创建 LocalDateTime
的实例。有一个 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
上次更新: 2022 年 1 月 27 日