文档

Java™ 教程-Java Tutorials 中文版
日期和时间类
Trail: Date Time
Lesson: Standard Calendar

日期和时间类

LocalTime

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 类不存储时区或夏令时信息。

LocalDateTime

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

除了每个基于时间的类提供的 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

Previous page: Date Classes
Next page: Time Zone and Offset Classes