前言
在Java开发中,日期和时间的处理是一个常见问题。为了简化这个过程,许多开发者会使用第三方工具包,如Hutool。Hutool是一个Java工具包,提供了许多实用的功能,其中之一就是日期处理。日期时间工具类是Hutool的核心包之一,提供针对JDK中Date和Calendar对象的封装,封装对象如下:
封装对象 | 说明 |
---|---|
DateUtil | 针对日期时间操作提供一系列静态方法 |
DateTime | 提供类似于Joda-Time中日期时间对象的封装,继承自Date类,并提供更加丰富的对象方法。 |
FastDateFormat | 提供线程安全的针对Date对象的格式化和日期字符串解析支持。 |
DateBetween | 计算两个时间间隔的类,除了通过构造新对象使用外,相关操作也已封装在DateUtil和DateTime的相关方法中。 |
TimeInterval | 一个简单的计时器类,常用于计算某段代码的执行时间,提供包括毫秒、秒、分、时、天、周等各种单位的花费时长计算。 |
DatePattern | 提供常用的日期格式化模式,包括String类型和FastDateFormat两种类型。 |
Quarter | 季度枚举 |
Month | 月份枚举 |
Week | 周枚举 |
DateUnit | 日期时间单位,表示某个时间单位对应的毫秒数,常用于计算时间差。 |
一、概述
1.1 工具简介
Hutool 的 DateUtil 工具类是 Hutool 工具库中用于日期和时间处理的核心类之一,提供了许多静态方法,用于方便地处理常见的日期和时间操作。考虑到 Java 本身对日期时间的支持有限,并且 Date 和 Calendar 对象的并存导致各种方法使用混乱和复杂,故使用此工具类做了封装。这其中的封装主要是日期和字符串之间的转换,以及提供对日期的定位。
1.2 引入依赖
在使用Hutool工具之前,我们需要将Hutool添加到项目的依赖中。如果使用Maven构建项目,可以在 pom.xml 文件中添加以下依赖:
<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
Hutool-all 是一个 Hutool 的集成打包产品,由于考虑到“懒人”用户及分不清各个模块作用的用户,“无脑”引入 hutool-all 模块是快速开始和深入应用的最佳方式。如果你想像 SpringBoot 一样引入 Hutool,再由子模块决定用到哪些模块,你可以在父模块中加入:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-bom</artifactId>
<version>${hutool.version}</version>
<type>pom</type>
<!-- 注意这里是import -->
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
然后再在子模块中就可以引入自己需要的模块了:
<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
</dependency>
</dependencies>
二、基本使用示例
2.1 计算生日
方法 | 部分参数 | 作用 |
---|---|---|
age(Date birthday, Date dateToCompare) | birthday:生日 dateToCompare:需要对比的日期 |
计算相对于dateToCompare的年龄,常用于计算指定生日在某年的年龄 |
ageOfNow(String birthDay) | birthDay:生日,标准日期字符串 | 生日转为年龄,计算法定年龄 |
ageOfNow(Date birthDay) | birthDay:生日 | 生日转为年龄,计算法定年龄 |
getChineseZodiac(int year) | 计算生肖,只计算1900年后出生的人 | |
getZodiac(int month, int day) | 通过生日计算星座 |
2.2 获取时间属性
2.2.1 获取当前时间
Hutool 提供了多种方式获取当前时间,例如当前时间戳、当前日期字符串等等。
方法 | 部分参数 | 作用 |
---|---|---|
DateTime date() | 将当前时间转换为DateTime对象 | |
DateTime date(Calendar calendar) | 根据已有 Calendar 转换为 DateTime对象 | |
DateTime dateSecond() | 当前时间,转换 DateTime 对象,忽略毫秒部分 | |
String now() | 当前时间,格式 yyyy-MM-dd HH:mm:ss | |
String today() | 当前日期,格式 yyyy-MM-dd | |
long current() | 当前时间的时间戳 | |
long currentSeconds() | 当前时间的时间戳(秒) |
2.2.2 获取当前时间属性
方法 | 部分参数 | 作用 |
---|---|---|
int getLastDayOfMonth(Date date) | 获得本月的最后一天 | |
int thisDayOfMonth() | 当前日期所在月份的第几周 | |
int thisDayOfWeek() | 当前日期是星期几 | |
int thisHour(boolean is24HourClock) | is24HourClock - 是否24小时制 | 当前日期的小时数部分 |
int thisMinute() | 当前日期的分钟数部分 | |
int thisMillisecond() | 当前日期的毫秒数部分 | |
int thisMonth() | 当前月份,从0开始计数 | |
int thisSecond() | 当前日期的秒数部分 | |
int thisWeekOfMonth() | 当前日期所在月份的第几周 | <