Hutool常用工具类及方法使用
)
依赖注入
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.7</version>
</dependency>
类型转换工具类 —— Convert
import cn.hutool.core.convert.Convert
//Convert.toLong —— 转为长整型
Long toLong = Convert.toLong("1,2"); //输出:12
//Convert.toStr —— 转换为字符串
String s = Convert.toStr(123); //输出:123
//Convert.convert(class,value,defaultValue) —— 转换为指定类型
//defaultValue可省略
Integer integer = Convert.convert(String.class, null, 33); //输出:33
//Convert.toBigDecimal() —— 转换为BigDecimal
BigDecimal decimal1 = Convert.toBigDecimal(12,new BigDecimal(15)); //输出:12
BigDecimal decimal2 = Convert.toBigDecimal(null, new BigDecimal(15)); //输出:15
//Convert.toBool —— 转换为Boolean
Boolean bool1 = Convert.toBool(1==2,true); //输出:false
Boolean bool2 = Convert.toBool(null,true); //输出:true
//Convert.toDate —— 转换为Date
Date date = Convert.toDate(null, new Date()); //输出:Thu Jan 13 09:00:00 CST 2022
toDouble(value,defaultValue)
toFloat(value,defaultValue)
toInt(value,defaultValue) ······
还有很多方便的类型转换,这里便不一一展示了,同理,defaultValue可省略。
时间工具类 —— DateUtil
import cn.hutool.core.date.DateUtil
//DateUtil.dayOfMonth —— 获取日期为所在月的第几天
int day = DateUtil.dayOfMonth(new Date()); //输出:13
//DateUtil.format —— 根据指定格式,转化时间
String format = DateUtil.format(new Date(), "yyyy-MM-dd"); //输出:2022-01-13
//DateUtil.year —— 获取年
int year = DateUtil.year(new Date()); //输出:2022
//DateUtil.formatDateTime —— 格式化日期时间
String time = DateUtil.formatDateTime(new Date()); //输出:2022-01-13 10:01:46
//DateUtil.lastMonth() —— 获取上个月
DateTime dateTime = DateUtil.lastMonth(); //输出:2021-12-13 10:04:59
//DateUtil.endOfYear() —— 获取年结束时间
DateTime dateTime = DateUtil.endOfYear(new Date());//输出:2022-12-31 23:59:59
···
字符串工具类 —— StrUtil
import cn.hutool.core.util.StrUtil
//生成uuid
String uuid = StrUtil.uuid();
//StrUtil.isBlankIfStr() —— 判断字符串是否为空白
/**
* 如果对象是字符串是否为空白,空白的定义如下:
* null
* 空字符串:""
* 空格、全角空格、制表符、换行符,等不可见字符
*/
StrUtil.isBlankIfStr(null) //输出: true
StrUtil.isBlankIfStr("") //输出: true
StrUtil.isBlankIfStr(" \t\n") //输出: true
StrUtil.isBlankIfStr("abc") //输出: false
身份证验证工具 —— IdcardUtil
//身份证号码是否有效
boolean idcard = IdcardUtil.isValidCard("000000000000000000");
//获取年龄 (身份证号码仅用于测试,如有雷同,纯属巧合)
int age1 = IdcardUtil.getAgeByIdCard("150303190102030405"); //输出:120
//获取指定日期时年龄 (身份证号码仅用于测试,如有雷同,纯属巧合)
int age2 = IdcardUtil.getAgeByIdCard("150303190102030405", DateUtil.parse("2020-01-01")); //输出:118
//获取生日 (身份证号码仅用于测试,如有雷同,纯属巧合)
String birth = IdcardUtil.getBirthByIdCard("150303190102030405");//输出:19010203
控制台打印 —— Console
Console可输出任意类型
int[] a = {1,2,3};
Console.log(a); //输出:[1, 2, 3]
String str = "java";
Console.log(str); //输出:java
BigDecimal decimal = new BigDecimal(1.1);
Console.log(decimal.setScale(4,BigDecimal.ROUND_HALF_DOWN)); //输出:1.1000