created: 2022-07-17T17:37:17+08:00
updated: 2022-07-23T13:10:34+08:00
tags:
- DateTimeAPI
- DateTimeAPI/LocalTime
- DateTimeAPI/LocalDateTime
Date and Time
The LocalTime Class
LocalTime
类似于名称以 Local 为前缀的其他类,但只处理时间。
LocalTime thisSec;
for (;;) {
thisSec = LocalTime.now();
// implementation of display code is left to the reader
display(thisSec.getHour(), thisSec.getMinute(), thisSec.getSecond());
}
LocalTime 类不存储时区或夏令时信息。
The LocalDateTime Class
处理日期和时间但没有时区的类是 LocalDateTime
,它是 Date-Time API 的核心类之一。此类用于表示日期(月-日-年)和时间(小时-分钟-秒-纳秒),实际上是 LocalDate
和 LocalTime
的组合。要包含时区,您必须使用 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));
result
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
[[时区和偏移量]]