日期和时间类

原文: https://docs.oracle.com/javase/tutorial/datetime/iso/datetime.html

当地时间

LocalTime 类类似于其名称以Local为前缀的其他类,但仅限时间处理。此类可用于表示基于人的时间,例如电影时间,或本地库的开始和结束时间。它还可用于创建数字时钟,如以下示例所示:

  1. LocalTime thisSec;
  2. for (;;) {
  3. thisSec = LocalTime.now();
  4. // implementation of display code is left to the reader
  5. display(thisSec.getHour(), thisSec.getMinute(), thisSec.getSecond());
  6. }

LocalTime类不存储时区或夏令时信息。

LocalDateTime

处理日期和时间而没有时区的类是 LocalDateTime,它是 Date-Time API 的核心类之一。此类用于表示日期(月 - 日 - 年)和时间(小时 - 分 - 秒 - 纳秒),实际上是LocalDateLocalTime的组合。本课程可用于表示特定事件,例如美国杯挑战者系列赛中路易威登杯决赛的首场比赛,该比赛于下午 1:10 开始。在 2013 年 8 月 17 日。请注意,这意味着下午 1:10。在当地时间。要包含时区,必须使用ZonedDateTimeOffsetDateTime ,如时区和偏移类中所述。

除了每个基于时间的类提供的现在方法之外, LocalDateTime类具有方法的各种(或者``的前缀方法) ])创建LocalDateTime的实例。来自方法的将实例从另一种时间格式转换为LocalDateTime`实例。还有添加或减去小时,分钟,天,周和月的方法。以下示例显示了其中一些方法。日期时间表达式以粗体显示:```java

  1. System.out.printf("now: %s%n", LocalDateTime.now());
  2. System.out.printf("Apr 15, 1994 @ 11:30am: %s%n",
  3. LocalDateTime.of(1994, Month.APRIL, 15, 11, 30));
  4. System.out.printf("now (from Instant): %s%n",
  5. LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()));
  6. System.out.printf("6 months from now: %s%n",
  7. LocalDateTime.now().plusMonths(6));
  8. System.out.printf("6 months ago: %s%n",
  9. LocalDateTime.now().minusMonths(6));
  10. ```java
  11. 此代码生成的输出类似于以下内容:

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

```