日期和时间类
原文: https://docs.oracle.com/javase/tutorial/datetime/iso/datetime.html
当地时间
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 的核心类之一。此类用于表示日期(月 - 日 - 年)和时间(小时 - 分 - 秒 - 纳秒),实际上是LocalDate
与LocalTime
的组合。本课程可用于表示特定事件,例如美国杯挑战者系列赛中路易威登杯决赛的首场比赛,该比赛于下午 1:10 开始。在 2013 年 8 月 17 日。请注意,这意味着下午 1:10。在当地时间。要包含时区,必须使用ZonedDateTime
或OffsetDateTime
,如时区和偏移类中所述。
除了每个基于时间的类提供的现在
方法之外, LocalDateTime
类具有方法的各种(或者``的前缀方法) ])创建
LocalDateTime的实例。来自
方法的将实例从另一种时间格式转换为
LocalDateTime`实例。还有添加或减去小时,分钟,天,周和月的方法。以下示例显示了其中一些方法。日期时间表达式以粗体显示:```java
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));
```java
此代码生成的输出类似于以下内容:
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
```