日期和时间

本文介绍了Java中的LocalTime和LocalDateTime类,详细阐述了它们的用途和方法,如now()、of()、plusMonths()等,展示了如何创建、操作和打印日期时间。LocalTime仅处理时间,而不包含时区信息,而LocalDateTime结合了日期和时间,但不涉及时区。示例代码演示了如何使用这些类进行日期时间的增减操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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 的核心类之一。此类用于表示日期(月-日-年)和时间(小时-分钟-秒-纳秒),实际上是 LocalDateLocalTime 的组合。要包含时区,您必须使用 ZonedDateTimeOffsetDateTime

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

[[时区和偏移量]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值