博客
关于我
java基础--22(java8新特性--时间和日期的API)
阅读量:691 次
发布时间:2019-03-17

本文共 3430 字,大约阅读时间需要 11 分钟。

Java 8 日期时间处理 实用指南

众所周知,Java 8 引入了新的日期时间API,这些API简化了日期时间的处理,提供了更强大的功能。以下是几个常用的类及其应用方法。


1. 重要的日期时间类

在 Java 8 中,有几个关键类值得了解:

  • LocalDate:表示本地日期,以 ISO 标准格式YYYY-MM-DD 存储。
  • LocalDateTime:表示本地日期和时间,格式为YYYY-MM-DD HH:mm。
  • LocalTime:表示本地时间段,格式为HH:mm。
  • Instant:表示时间轴上的绝对时间点(相当于 UTC 时间)。
  • Duration:表示两个绝对时间点之间的时间间隔。
  • Period:表示两个本地时间间隔。
  • TemporalAdjusters:提供日期调整功能,可用于创建自定义的日期调整器。

这些类为开发人员提供了更直观的操作日期时间的方法,同时保留了对时区和闰年的正确处理。


2. 本地时间处理

大多数情况下,我们需要与本地系统时间相关的操作,比如生日、假日、会议等。在 Java 8 中,LocalDateLocalDateTimeLocalTime 都用于表示本地时间。

  • LocalDate:主要用于日期操作,如增加减少日期、判断闰年等。
  • LocalDateTime:用于完整的日期和时间表示,包括小时、分钟等细粒度。
  • LocalTime:用于单独表示时间段,不带日期信息。

这些类的创建和操作方法相似,通过将 DateTimeFormatter 或 TemporalAdjuster 过Joseab.idc accordance 初始化,可以灵活地进行日期时间操作。


3. 绝对时间的表示

Instant 类用于表示时间轴上的绝对时间点,基于 UTC 标准时间。这意味着它不受时区影响,可以通过它获取绝对时间间隔或进行比较。

Duration 类则用于计算两个 Instant 之间的时间间隔,可以进行加减操作,或者与其他 Duration 比较。

由于这些类都是 final 类,所有方法不会修改原对象,而是返回新的对象,使得代码更安全且不容易出错。


4. 本地时间的高级操作

Period 类可以用来计算本地时间间隔。例如,获取两个本地日期之间的时间差。

TemporalAdjusters 则提供了日期调整功能。它有一个默认的调整器库,但开发者也可以实现自定义的 TemporalAdjuster 接口,从而定制特定的日期调整逻辑。例如,可以编写一个调整器,使得日期滚动到下一个工作日。


5. 时区的处理

如果需要处理带时区的时间,可以使用 ZonedDateTime 类。它类似于前传 Calendar,但具有现代化的API。

通过指定不同的 ZoneId,开发人员可以轻松转换时间到不同时区。例如,将北京时间和纽约时间进行比较,就可以直观地了解两地时间差异。


6. 日期时间格式化与解析

DateTimeFormatter 类用于格式化日期时间为字符串,支持多种格式化模式,如 "yyyy-MM-dd HH:mm"。它同时支持反向操作,即将字符串解析为 DateTime 对象。


7. 示例代码解析

以下是一些典型的代码示例:

1. 时间发送时间选择将来

public void checkSendDate(Date sendDate) {    Instant instant = sendDate.toInstant();    ZoneId zoneId = ZoneId.systemDefault();    LocalDateTime nowLocalDateTime = LocalDateTime.now();    LocalDateTime sendLocalDateTime = instant.atZone(zoneId).toLocalDateTime();    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");    String strNowLocalDateTime = nowLocalDateTime.format(formatter);    String strSendLocalDateTime = sendLocalDateTime.format(formatter);    nowLocalDateTime = LocalDateTime.parse(strNowLocalDateTime, formatter);    sendLocalDateTime = LocalDateTime.parse(strSendLocalDateTime, formatter);    if (sendLocalDateTime.isBefore(nowLocalDateTime)) {        throw new CommonException("error.send.time");    }}

该方法确保发送时间选定的将来。如果 sendDate 小于当前时间,会抛出错误异常。

2. 间隔控制

public void checkQueryByDate(ArtCalendarEventVO artCalendarEventVO) {    ZoneId zoneId = ZoneId.systemDefault();    if (artCalendarEventVO.getStartDate() != null && artCalendarEventVO.getEndDate() != null) {        LocalDate startDate = artCalendarEventVO.getStartDate().toInstant().atZone(zoneId).toLocalDate();        LocalDate endDate = artCalendarEventVO.getEndDate().toInstant().atZone(zoneId).toLocalDate();        if (endDate.toEpochDay() - startDate.toEpochDay() > 180) {            throw new CommonException("error.lastTime.too.long");        }    }    if (artCalendarEventVO.getStartDate() != null && artCalendarEventVO.getEndDate() == null) {        LocalDateTime localDateTime = artCalendarEventVO.getStartDate().toInstant().atZone(zoneId).toLocalDateTime();        artCalendarEventVO.setEndDate(Date.from(localDateTime.plusDays(180).atZone(zoneId).toInstant()));    }    if (artCalendarEventVO.getEndDate() != null && artCalendarEventVO.getStartDate() == null) {        LocalDateTime localDateTime = artCalendarEventVO.getEndDate().toInstant().atZone(zoneId).toLocalDateTime();        artCalendarEventVO.setStartDate(Date.from(localDateTime.minusDays(180).atZone(zoneId).toInstant()));    }}

该方法用于检查时间间隔,确保间隔不超过 180 天。


通过这些工具,开发者可以更简便地处理日期和时间问题,同时保持代码的清晰和可维护性。

转载地址:http://eahhz.baihongyu.com/

你可能感兴趣的文章
MySQL 数据类型和属性
查看>>
mysql 敲错命令 想取消怎么办?
查看>>
Mysql 整形列的字节与存储范围
查看>>
mysql 断电数据损坏,无法启动
查看>>
MySQL 日期时间类型的选择
查看>>
Mysql 时间操作(当天,昨天,7天,30天,半年,全年,季度)
查看>>
MySQL 是如何加锁的?
查看>>
MySQL 是怎样运行的 - InnoDB数据页结构
查看>>
mysql 更新子表_mysql 在update中实现子查询的方式
查看>>
MySQL 有什么优点?
查看>>
mysql 权限整理记录
查看>>
mysql 权限登录问题:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)
查看>>
MYSQL 查看最大连接数和修改最大连接数
查看>>
MySQL 查看有哪些表
查看>>
mysql 查看锁_阿里/美团/字节面试官必问的Mysql锁机制,你真的明白吗
查看>>
MySql 查询以逗号分隔的字符串的方法(正则)
查看>>
MySQL 查询优化:提速查询效率的13大秘籍(避免使用SELECT 、分页查询的优化、合理使用连接、子查询的优化)(上)
查看>>
mysql 查询数据库所有表的字段信息
查看>>
【Java基础】什么是面向对象?
查看>>
mysql 查询,正数降序排序,负数升序排序
查看>>