Hutool工具介绍

Hutool工具介绍

1)Hutool基本介绍
  1. hutool是一个java工具包,对于初学者来说是一个降低门槛,快速上手,避免踩坑,学习教材的工具,对于有经验者来说是一个提高效率,完善知识的工具。
  2. Hutool的目标是使用一个工具方法代替一段复杂的代码,最大限度避免"复制粘贴"代码的问题。
  3. Hutool优势:
    1. 代码风格时候国内开发习惯。
    2. 代码注释文档全中文,阅读零门槛。
    3. 工具方法多,学习难度低。
  4. Hutool劣势:
    1. 代码没有结果严格的单元测试把关。
    2. 工程级项目不适合。 (原因:工程级项目追求稳定,尽量使用有专业团队维护的工具类,例如: apache, google工具类)
  5. 工具类优先级选择
    1.在这里插入图片描述
2)包含组件
  1. 功能模块分类

    模板内容
    hutool-aopJDK动态代理封装,提供非IOC下的切面支持
    hutool-bloomFilter布隆过滤,提供一些Hash算法的布隆过滤
    hutool-cache简单缓存实现
    hutool-core核心,包括Bean操作、日期、各种Util等
    hutool-cron定时任务模块,提供类Crontab表达式的定时任务
    hutool-crypto加密解密模块,提供对称、非对称和摘要算法封装
    hutool-dbJDBC封装后的数据操作,基于ActiveRecord思想
    hutool-dfa基于DFA模型的多关键字查找
    hutool-extra扩展模块,对第三方封装(模板引擎、邮件、Servlet、二维码、Emoji、FTP、分词等)
    hutool-http基于HttpUrlConnection的Http客户端封装
    hutool-log自动识别日志实现的日志门面
    hutool-script脚本执行封装,例如Javascript
    hutool-setting功能更强大的Setting配置文件和Properties封装
    hutool-system系统参数调用封装(JVM信息等)
    hutool-jsonJSON实现
    hutool-captcha图片验证码实现
    hutool-poi针对POI中Excel和Word的封装
    hutool-socket基于Java的NIO和AIO的Socket封装
    hutool-jwtJSON Web Token (JWT)封装实现
3) Hutool使用
  1. <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.5.7</version>
    </dependency>
    <!--
    1.版本方面:Hutool 5.x支持JDK8。 如果项目使用的是JDK7,请使用Hutool 4.x版本;
    2.引入模块方面:可以根据需求对每个模块单独引入,也可以通过引入hutool-all方式引入所有模块。 
    -->
    
4)Hutool-core介绍
  1. 泛型克隆;

    1. package cn.hutool.core.clone;
      // 实现Cloneable接口
      public interface Cloneable<T> extends java.lang.Cloneable {
          T clone();
      }
      
    2. package cn.hutool.core.clone;
      //实现CloneSupport类
      public class CloneSupport<T> implements Cloneable<T>{
      
      	@Override
      	public T clone() {
      		try {
      			return (T) super.clone();
      		} catch (CloneNotSupportedException e) {
      			throw new CloneRuntimeException(e);
      		}
      	}
      }
      
    3. 底层 -->

      1. hutool.Cloneable继承JDK中的Cloneable接口,重写Object下clone()方法。
      2. JDK中的Cloneable接口只是一个空接口,没有定义成员。指明一个类的实例化对象支持复制,如果不实现这个类调用对象的clone()方法就会抛出CloneNotSupportedException异常。clone()方法在Object对象中 返回值也是Object对象 克隆后强转类型。
  2. Convert类

    1. 功能:类型转换。

    2. 优点:万能。多种转换器基本满足所有需求。

    3. 常用方法

      //转换为字符串
      int a = 1;
      String aStr = Convert.toStr(a);
      //转换为指定类型数组
      String[] b = {"1", "2", "3", "4"};
      Integer[] bArr = Convert.toIntArray(b);
      //转换为日期对象
      String dateStr = "2017-05-06";
      Date date = Convert.toDate(dateStr);
      //转换为列表
      String[] strArr = {"a", "b", "c", "d"};
      List<String> strList = Convert.toList(String.class, strArr);
      //泛型
      Object[] a = { "a", "你", "好", "", 1 };
      List<String> list = Convert.convert(new TypeReference<List<String>>() {}, a);
      
    4. 底层—>

      /**
      	 * 转换值为指定类型
      	 *
      	 * @param <T>           转换的目标类型(转换器转换到的类型)
      	 * @param type          类型目标
      	 * @param value         被转换值
      	 * @param defaultValue  默认值
      	 * @param isCustomFirst 是否自定义转换器优先
      	 * @return 转换后的值
      	 * @throws ConvertException 转换器不存在
      	 */
      	@SuppressWarnings("unchecked")
      	public <T> T convert(Type type, Object value, T defaultValue, boolean isCustomFirst) throws ConvertException {
      		if (TypeUtil.isUnknown(type) && null == defaultValue) {
      			// 对于用户不指定目标类型的情况,返回原值
      			return (T) value;
      		}
      		if (ObjectUtil.isNull(value)) {
      			return defaultValue;
      		}
      		if (TypeUtil.isUnknown(type)) {
      			type = defaultValue.getClass();
      		}
      
      		if (type instanceof TypeReference) {
      			type = ((TypeReference<?>) type).getType();
      		}
      
      		// 自定义对象转换
      		if(value instanceof TypeConverter){
      			return ObjUtil.defaultIfNull((T) ((TypeConverter) value).convert(type, value), defaultValue);
      		}
      
      		// 标准转换器
      		final Converter<T> converter = getConverter(type, isCustomFirst);
      		if (null != converter) {
      			return converter.convert(value, defaultValue);
      		}
      
      		Class<T> rowType = (Class<T>) TypeUtil.getClass(type);
      		if (null == rowType) {
      			if (null != defaultValue) {
      				rowType = (Class<T>) defaultValue.getClass();
      			} else {
      				// 无法识别的泛型类型,按照Object处理
      				return (T) value;
      			}
      		}
      
      		// 特殊类型转换,包括Collection、Map、强转、Array等
      		final T result = convertSpecial(type, rowType, value, defaultValue);
      		if (null != result) {
      			return result;
      		}
      
      		// 尝试转Bean
      		if (BeanUtil.isBean(rowType)) {
      			return new BeanConverter<T>(type).convert(value, defaultValue);
      		}
      
      		// 无法转换
      		throw new ConvertException("Can not Converter from [{}] to [{}]", value.getClass().getName(), type.getTypeName());
      	}
      
      
  3. 日期时间工具 DateUtil

    1. package cn.hutool.core.date;
      
      
      public class DateUtil extends CalendarUtil {
          private static final String[] wtb = new String[]{"sun", "mon", "tue", "wed", "thu", "fri", "sat", "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", "gmt", "ut", "utc", "est", "edt", "cst", "cdt", "mst", "mdt", "pst", "pdt"};
      
          public DateUtil() {
          }
         // 返回当前最新DateTime
          public static DateTime date() {
              return new DateTime();
          }
         // 返回当前精确到秒最新DateTime
          public static DateTime dateSecond() {
              return beginOfSecond(date());
          }
         // 返回当前DateTime
          public static DateTime date(Date date) {
              return date instanceof DateTime ? (DateTime)date : dateNew(date);
          }
         // 返回当前最新DateTime
          public static DateTime dateNew(Date date) {
              return new DateTime(date);
          }
         // 通过时间戳返回当前DateTime
          public static DateTime date(long date) {
              return new DateTime(date);
          }
         // 通过日历返回当前DateTime
          public static DateTime date(Calendar calendar) {
              return new DateTime(calendar);
          }
          // 通过格式化器返回当前DateTime
          public static DateTime date(TemporalAccessor temporalAccessor) {
              return new DateTime(temporalAccessor);
          }
          // 返回毫秒时间戳
          public static long current() {
              return System.currentTimeMillis();
          }
          // 返回秒时间戳
          public static long currentSeconds() {
              return System.currentTimeMillis() / 1000L;
          }
          // 返回格式化时间字符串
          public static String now() {
              return formatDateTime(new DateTime());
          }
          // 返回格式化时间字符串
          public static String today() {
              return formatDate(new DateTime());
          }
          // 返回第几季度(3个月一个季度)数字
          public static int year(Date date) {
              return DateTime.of(date).year();
          }
          // 返回第几季度(3个月一个季度)文字
          public static int quarter(Date date) {
              return DateTime.of(date).quarter();
          }
          // 获得指定日期所属季度
          public static Quarter quarterEnum(Date date) {
              return DateTime.of(date).quarterEnum();
          }
          // 获得当前月份
          public static int month(Date date) {
              return DateTime.of(date).month();
          }
          // 获得月份枚举
          public static Month monthEnum(Date date) {
              return DateTime.of(date).monthEnum();
          }
           // 获得指定日期是所在年份的第几周
          public static int weekOfYear(Date date) {
              return DateTime.of(date).weekOfYear();
          }
           // 获得指定日期是所在月份的第几周
          public static int weekOfMonth(Date date) {
              return DateTime.of(date).weekOfMonth();
          }
         // 获得指定日期是所在月份的第几天
          public static int dayOfMonth(Date date) {
              return DateTime.of(date).dayOfMonth();
          }
         // 获得指定日期是所在年份的第几天
          public static int dayOfYear(Date date) {
              return DateTime.of(date).dayOfYear();
          }
         // 获得指定日期是所在周的第几天
          public static int dayOfWeek(Date date) {
              return DateTime.of(date).dayOfWeek();
          }
         // 获得指定日期是所在星期的第几天枚举
          public static Week dayOfWeekEnum(Date date) {
              return DateTime.of(date).dayOfWeekEnum();
          }
         // 获得指定日期是否是周末
          public static boolean isWeekend(Date date) {
              Week week = dayOfWeekEnum(date);
              return Week.SATURDAY == week || Week.SUNDAY == week;
          }
         // 获得指定日期获取小时
          public static int hour(Date date, boolean is24HourClock) {
              return DateTime.of(date).hour(is24HourClock);
          }
         // 获得指定日期获取分钟
          public static int minute(Date date) {
              return DateTime.of(date).minute();
          }
         // 获得指定日期获取秒
          public static int second(Date date) {
              return DateTime.of(date).second();
          }
         // 获得指定日期获取毫秒
          public static int millisecond(Date date) {
              return DateTime.of(date).millisecond();
          }
         // 获得指定日期是否上午
          public static boolean isAM(Date date) {
              return DateTime.of(date).isAM();
          }
         // 获得指定日期是否下午
          public static boolean isPM(Date date) {
              return DateTime.of(date).isPM();
          }
          // 今年
          public static int thisYear() {
              return year(date());
          }
          // 当前月份
          public static int thisMonth() {
              return month(date());
          }
          // 当前月份枚举
          public static Month thisMonthEnum() {
              return monthEnum(date());
          }
          // 当前日期所在年份的第几周
          public static int thisWeekOfYear() {
              return weekOfYear(date());
          }
          // 当前日期所在月份的第几周
          public static int thisWeekOfMonth() {
              return weekOfMonth(date());
          }
          // 当前日期所在月份的第几天
          public static int thisDayOfMonth() {
              return dayOfMonth(date());
          }
          // 当前日期是星期几
          public static int thisDayOfWeek() {
              return dayOfWeek(date());
          }
          // 当前日期是星期几枚举
          public static Week thisDayOfWeekEnum() {
              return dayOfWeekEnum(date());
          }
          // 当前日期的小时数部分 是否24小时制
          public static int thisHour(boolean is24HourClock) {
              return hour(date(), is24HourClock);
          }
          // 当前日期的分钟数部分
          public static int thisMinute() {
              return minute(date());
          }
          // 当前日期的秒数部分
          public static int thisSecond() {
              return second(date());
          }
          // 当前日期的毫秒数部分
          public static int thisMillisecond() {
              return millisecond(date());
          }
      	// 获得指定日期年份和季节字符串
          public static String yearAndQuarter(Date date) {
              return yearAndQuarter(calendar(date));
          }
      	// 获得指定日期年份和季节 Set字符串
          public static LinkedHashSet<String> yearAndQuarter(Date startDate, Date endDate) {
              return startDate != null && endDate != null ? yearAndQuarter(startDate.getTime(), endDate.getTime()) : new LinkedHashSet(0);
          }
      	// 格式化日期时间<br> 格式 yyyy-MM-dd HH:mm:ss
          public static String formatLocalDateTime(LocalDateTime localDateTime) {
              return LocalDateTimeUtil.formatNormal(localDateTime);
          }
      	// 根据特定格式格式化日期
          public static String format(LocalDateTime localDateTime, String format) {
              return LocalDateTimeUtil.format(localDateTime, format);
          }
      	// 根据特定格式格式化日期
          public static String format(Date date, String format) {
              if (null != date && !StrUtil.isBlank(format)) {
                  if (GlobalCustomFormat.isCustomFormat(format)) {
                      return GlobalCustomFormat.format(date, format);
                  } else {
                      TimeZone timeZone = null;
                      if (date instanceof DateTime) {
                          timeZone = ((DateTime)date).getTimeZone();
                      }
      
                      return format((Date)date, (DateFormat)newSimpleFormat(format, (Locale)null, timeZone));
                  }
              } else {
                  return null;
              }
          }
      	// 根据特定格式格式化日期
          public static String format(Date date, DatePrinter format) {
              return null != format && null != date ? format.format(date) : null;
          }
      	// 根据特定格式格式化日期
          public static String format(Date date, DateFormat format) {
              return null != format && null != date ? format.format(date) : null;
          }
      	// 根据特定格式格式化日期
          public static String format(Date date, DateTimeFormatter format) {
              return null != format && null != date ? TemporalAccessorUtil.format(date.toInstant(), format) : null;
          }
      	// 格式化日期时间<br> 格式 yyyy-MM-dd HH:mm:ss
          public static String formatDateTime(Date date) {
              return null == date ? null : DatePattern.NORM_DATETIME_FORMAT.format(date);
          }
      	// 格式化日期部分(不包括时间)<br> 格式 yyyy-MM-dd
          public static String formatDate(Date date) {
              return null == date ? null : DatePattern.NORM_DATE_FORMAT.format(date);
          }
      	// 格式化日期部分(不包括时间)<br> 格式 HH:mm:ss
          public static String formatTime(Date date) {
              return null == date ? null : DatePattern.NORM_TIME_FORMAT.format(date);
          }
      	// 格式化日期部分(不包括时间)<br> 格式  dd MMM yyyy HH:mm:ss z
          public static String formatHttpDate(Date date) {
              return null == date ? null : DatePattern.HTTP_DATETIME_FORMAT.format(date);
          }
      	// 格式化为中文日期格式,如果isUppercase为false,则返回类似:2018年10月24日,否则返回二〇一八年十月二十四日
          public static String formatChineseDate(Date date, boolean isUppercase, boolean withTime) {
              if (null == date) {
                  return null;
              } else {
                  return !isUppercase ? (withTime ? DatePattern.CHINESE_DATE_TIME_FORMAT : DatePattern.CHINESE_DATE_FORMAT).format(date) : CalendarUtil.formatChineseDate(CalendarUtil.calendar(date), withTime);
              }
          }
          // 构建LocalDateTime对象格式:yyyy-MM-dd HH:mm:ss
          public static LocalDateTime parseLocalDateTime(CharSequence dateStr) {
              return parseLocalDateTime(dateStr, "yyyy-MM-dd HH:mm:ss");
          }
          // 构建LocalDateTime对象
          public static LocalDateTime parseLocalDateTime(CharSequence dateStr, String format) {
              return LocalDateTimeUtil.parse(dateStr, format);
          }
          // 构建DateTime对象
          public static DateTime parse(CharSequence dateStr, DateFormat dateFormat) {
              return new DateTime(dateStr, dateFormat);
          }
          // 构建DateTime对象
          public static DateTime parse(CharSequence dateStr, DateParser parser) {
              return new DateTime(dateStr, parser);
          }
          // 构建DateTime对象
          public static DateTime parse(CharSequence dateStr, DateParser parser, boolean lenient) {
              return new DateTime(dateStr, parser, lenient);
          }
          // 构建DateTime对象
          public static DateTime parse(CharSequence dateStr, DateTimeFormatter formatter) {
              return new DateTime(dateStr, formatter);
          }
          // 构建DateTime对象
          public static DateTime parse(CharSequence dateStr, String format) {
              return new DateTime(dateStr, format);
          }
          // 构建DateTime对象
          public static DateTime parse(CharSequence dateStr, String format, Locale locale) {
              return GlobalCustomFormat.isCustomFormat(format) ? new DateTime(GlobalCustomFormat.parse(dateStr, format)) : new DateTime(dateStr, newSimpleFormat(format, locale, (TimeZone)null));
          }
          // 构建DateTime对象
          public static DateTime parse(String str, String... parsePatterns) throws DateException {
              return new DateTime(CalendarUtil.parseByPatterns(str, parsePatterns));
          }
          // 构建DateTime对象(yyyy-MM-dd HH:mm:ss)
          public static DateTime parseDateTime(CharSequence dateString) {
              CharSequence dateString = normalize(dateString);
              return parse((CharSequence)dateString, (DateParser)DatePattern.NORM_DATETIME_FORMAT);
          }
          // 构建DateTime对象(yyyy-MM-dd)
          public static DateTime parseDate(CharSequence dateString) {
              CharSequence dateString = normalize(dateString);
              return parse((CharSequence)dateString, (DateParser)DatePattern.NORM_DATE_FORMAT);
          }
          // 构建DateTime对象(HH:mm:ss)
          public static DateTime parseTime(CharSequence timeString) {
              CharSequence timeString = normalize(timeString);
              return parse((CharSequence)timeString, (DateParser)DatePattern.NORM_TIME_FORMAT);
          }
          // 解析时间,格式HH:mm 或 HH:mm:ss,日期默认为今天
          public static DateTime parseTimeToday(CharSequence timeString) {
              CharSequence timeString = StrUtil.format("{} {}", new Object[]{today(), timeString});
              return 1 == StrUtil.count(timeString, ':') ? parse((CharSequence)timeString, (String)"yyyy-MM-dd HH:mm") : parse((CharSequence)timeString, (DateParser)DatePattern.NORM_DATETIME_FORMAT);
          }
         // 解析UTC时间,格式:yyyy-MM-dd’T’HH:mm:ss’Z’yyyy-MM-dd’T’HH:mm:ss.SSS’Z’yyyy-MM-dd’T’HH:mm:ssZ yyyy-MM-dd’T’HH:mm:ss.SSSZ
          public static DateTime parseUTC(String utcString) {
              if (utcString == null) {
                  return null;
              } else {
                  int length = utcString.length();
                  if (StrUtil.contains(utcString, 'Z')) {
                      if (length == "yyyy-MM-dd'T'HH:mm:ss'Z'".length() - 4) {
                          return parse((CharSequence)utcString, (DateParser)DatePattern.UTC_FORMAT);
                      }
      
                      int patternLength = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'".length();
                      if (length <= patternLength - 4 && length >= patternLength - 6) {
                          return parse((CharSequence)utcString, (DateParser)DatePattern.UTC_MS_FORMAT);
                      }
                  } else {
                      if (StrUtil.contains(utcString, '+')) {
                          utcString = utcString.replace(" +", "+");
                          String zoneOffset = StrUtil.subAfter(utcString, '+', true);
                          if (StrUtil.isBlank(zoneOffset)) {
                              throw new DateException("Invalid format: [{}]", new Object[]{utcString});
                          }
      
                          if (!StrUtil.contains(zoneOffset, ':')) {
                              String pre = StrUtil.subBefore(utcString, '+', true);
                              utcString = pre + "+" + zoneOffset.substring(0, 2) + ":00";
                          }
      
                          if (StrUtil.contains(utcString, '.')) {
                              return parse((CharSequence)utcString, (DateParser)DatePattern.UTC_MS_WITH_XXX_OFFSET_FORMAT);
                          }
      
                          return parse((CharSequence)utcString, (DateParser)DatePattern.UTC_WITH_XXX_OFFSET_FORMAT);
                      }
      
                      if (ReUtil.contains("-\\d{2}:?00", utcString)) {
                          utcString = utcString.replace(" -", "-");
                          if (':' != utcString.charAt(utcString.length() - 3)) {
                              utcString = utcString.substring(0, utcString.length() - 2) + ":00";
                          }
      
                          if (StrUtil.contains(utcString, '.')) {
                              return new DateTime(utcString, DatePattern.UTC_MS_WITH_XXX_OFFSET_FORMAT);
                          }
      
                          return new DateTime(utcString, DatePattern.UTC_WITH_XXX_OFFSET_FORMAT);
                      }
      
                      if (length == "yyyy-MM-dd'T'HH:mm:ss".length() - 2) {
                          return parse((CharSequence)utcString, (DateParser)DatePattern.UTC_SIMPLE_FORMAT);
                      }
      
                      if (length == "yyyy-MM-dd'T'HH:mm:ss".length() - 5) {
                          return parse((CharSequence)(utcString + ":00"), (DateParser)DatePattern.UTC_SIMPLE_FORMAT);
                      }
      
                      if (StrUtil.contains(utcString, '.')) {
                          return parse((CharSequence)utcString, (DateParser)DatePattern.UTC_SIMPLE_MS_FORMAT);
                      }
                  }
      
                  throw new DateException("No format fit for date String [{}] !", new Object[]{utcString});
              }
          }
         // 解析CST时间,格式:EEE MMM dd HH:mm:ss z yyyy(例如:Wed Aug 01 00:00:00 CST 2012)
          public static DateTime parseCST(CharSequence cstString) {
              return cstString == null ? null : parse((CharSequence)cstString, (DateParser)DatePattern.JDK_DATETIME_FORMAT);
          }
        // 将日期字符串转换为{@link DateTime}对象
          public static DateTime parse(CharSequence dateCharSequence) {
              if (StrUtil.isBlank(dateCharSequence)) {
                  return null;
              } else {
                  String dateStr = dateCharSequence.toString();
                  dateStr = StrUtil.removeAll(dateStr.trim(), new char[]{'日', '秒'});
                  int length = dateStr.length();
                  if (NumberUtil.isNumber(dateStr)) {
                      if (length == "yyyyMMddHHmmss".length()) {
                          return parse((CharSequence)dateStr, (DateParser)DatePattern.PURE_DATETIME_FORMAT);
                      }
      
                      if (length == "yyyyMMddHHmmssSSS".length()) {
                          return parse((CharSequence)dateStr, (DateParser)DatePattern.PURE_DATETIME_MS_FORMAT);
                      }
      
                      if (length == "yyyyMMdd".length()) {
                          return parse((CharSequence)dateStr, (DateParser)DatePattern.PURE_DATE_FORMAT);
                      }
      
                      if (length == "HHmmss".length()) {
                          return parse((CharSequence)dateStr, (DateParser)DatePattern.PURE_TIME_FORMAT);
                      }
                  } else {
                      if (ReUtil.isMatch(PatternPool.TIME, dateStr)) {
                          return parseTimeToday(dateStr);
                      }
      
                      if (StrUtil.containsAnyIgnoreCase(dateStr, wtb)) {
                          return parseCST(dateStr);
                      }
      
                      if (StrUtil.contains(dateStr, 'T')) {
                          return parseUTC(dateStr);
                      }
                  }
      
                  dateStr = normalize(dateStr);
                  if (ReUtil.isMatch(DatePattern.REGEX_NORM, dateStr)) {
                      int colonCount = StrUtil.count(dateStr, ':');
                      switch(colonCount) {
                      case 0:
                          return parse((CharSequence)dateStr, (DateParser)DatePattern.NORM_DATE_FORMAT);
                      case 1:
                          return parse((CharSequence)dateStr, (DateParser)DatePattern.NORM_DATETIME_MINUTE_FORMAT);
                      case 2:
                          int indexOfDot = StrUtil.indexOf(dateStr, '.');
                          if (indexOfDot > 0) {
                              int length1 = dateStr.length();
                              if (length1 - indexOfDot > 4) {
                                  dateStr = StrUtil.subPre(dateStr, indexOfDot + 4);
                              }
      
                              return parse((CharSequence)dateStr, (DateParser)DatePattern.NORM_DATETIME_MS_FORMAT);
                          }
      
                          return parse((CharSequence)dateStr, (DateParser)DatePattern.NORM_DATETIME_FORMAT);
                      }
                  }
      
                  throw new DateException("No format fit for date String [{}] !", new Object[]{dateStr});
              }
          }
       	// 修改日期为某个时间字段起始时间
          public static DateTime truncate(Date date, DateField dateField) {
              return new DateTime(truncate(calendar(date), dateField));
          }
      	// 修改日期为某个时间字段四舍五入时间
          public static DateTime round(Date date, DateField dateField) {
              return new DateTime(round(calendar(date), dateField));
          }
      	// 修改日期为某个时间字段结束时间
          public static DateTime ceiling(Date date, DateField dateField) {
              return new DateTime(ceiling(calendar(date), dateField));
          }
      	// 修改日期为某个时间字段结束时间
          public static DateTime ceiling(Date date, DateField dateField, boolean truncateMillisecond) {
              return new DateTime(ceiling(calendar(date), dateField, truncateMillisecond));
          }
       	// 获取秒级别的开始时间,即忽略毫秒部分
          public static DateTime beginOfSecond(Date date) {
              return new DateTime(beginOfSecond(calendar(date)));
          }
      	// 获取秒级别的结束时间,即毫秒设置为999
          public static DateTime endOfSecond(Date date) {
              return new DateTime(endOfSecond(calendar(date)));
          }
      	// 获取某小时的开始时间
          public static DateTime beginOfHour(Date date) {
              return new DateTime(beginOfHour(calendar(date)));
          }
      	// 获取某小时的结束时间
          public static DateTime endOfHour(Date date) {
              return new DateTime(endOfHour(calendar(date)));
          }
      	// 获取某分钟的开始时间
          public static DateTime beginOfMinute(Date date) {
              return new DateTime(beginOfMinute(calendar(date)));
          }
      	// 获取某分钟的结束时间
          public static DateTime endOfMinute(Date date) {
              return new DateTime(endOfMinute(calendar(date)));
          }
      	// 获取某天的开始时间
          public static DateTime beginOfDay(Date date) {
              return new DateTime(beginOfDay(calendar(date)));
          }
      	// 获取某天的结束时间
          public static DateTime endOfDay(Date date) {
              return new DateTime(endOfDay(calendar(date)));
          }
      	// 获取某周的开始时间,周一定为一周的开始时间
          public static DateTime beginOfWeek(Date date) {
              return new DateTime(beginOfWeek(calendar(date)));
          }
      	// 获取某周的开始时间
          public static DateTime beginOfWeek(Date date, boolean isMondayAsFirstDay) {
              return new DateTime(beginOfWeek(calendar(date), isMondayAsFirstDay));
          }
      	// 获取某周的结束时间,周日定为一周的结束
          public static DateTime endOfWeek(Date date) {
              return new DateTime(endOfWeek(calendar(date)));
          }
      	// 获取某周的结束时间
          public static DateTime endOfWeek(Date date, boolean isSundayAsLastDay) {
              return new DateTime(endOfWeek(calendar(date), isSundayAsLastDay));
          }
      	// 获取某月的开始时间
          public static DateTime beginOfMonth(Date date) {
              return new DateTime(beginOfMonth(calendar(date)));
          }
      	// 获取某月的结束时间
          public static DateTime endOfMonth(Date date) {
              return new DateTime(endOfMonth(calendar(date)));
          }
      	// 获取某季度的开始时间
          public static DateTime beginOfQuarter(Date date) {
              return new DateTime(beginOfQuarter(calendar(date)));
          }
      	// 获取某季度的结束时间
          public static DateTime endOfQuarter(Date date) {
              return new DateTime(endOfQuarter(calendar(date)));
          }
      	// 获取某年的开始时间
          public static DateTime beginOfYear(Date date) {
              return new DateTime(beginOfYear(calendar(date)));
          }
      	// 获取某年的结束时间
          public static DateTime endOfYear(Date date) {
              return new DateTime(endOfYear(calendar(date)));
          }
      	// 昨天
          public static DateTime yesterday() {
              return offsetDay(new DateTime(), -1);
          }
      	// 明天
          public static DateTime tomorrow() {
              return offsetDay(new DateTime(), 1);
          }
      	// 上周
          public static DateTime lastWeek() {
              return offsetWeek(new DateTime(), -1);
          }
      	// 下周
          public static DateTime nextWeek() {
              return offsetWeek(new DateTime(), 1);
          }
      	// 上个月
          public static DateTime lastMonth() {
              return offsetMonth(new DateTime(), -1);
          }
      	// 下个月
          public static DateTime nextMonth() {
              return offsetMonth(new DateTime(), 1);
          }
      	// 偏移毫秒数
          public static DateTime offsetMillisecond(Date date, int offset) {
              return offset(date, DateField.MILLISECOND, offset);
          }
      	// 偏移秒数
          public static DateTime offsetSecond(Date date, int offset) {
              return offset(date, DateField.SECOND, offset);
          }
      	// 偏移分钟
          public static DateTime offsetMinute(Date date, int offset) {
              return offset(date, DateField.MINUTE, offset);
          }
      	// 偏移小时
          public static DateTime offsetHour(Date date, int offset) {
              return offset(date, DateField.HOUR_OF_DAY, offset);
          }
      	// 偏移天
          public static DateTime offsetDay(Date date, int offset) {
              return offset(date, DateField.DAY_OF_YEAR, offset);
          }
      	// 偏移周
          public static DateTime offsetWeek(Date date, int offset) {
              return offset(date, DateField.WEEK_OF_YEAR, offset);
          }
      	// 偏移月
          public static DateTime offsetMonth(Date date, int offset) {
              return offset(date, DateField.MONTH, offset);
          }
      	// 获取指定日期偏移指定时间后的时间,生成的偏移日期不影响原日期
          public static DateTime offset(Date date, DateField dateField, int offset) {
              return dateNew(date).offset(dateField, offset);
          }
      	// 判断两个日期相差的时长,只保留绝对值
          public static long between(Date beginDate, Date endDate, DateUnit unit) {
              return between(beginDate, endDate, unit, true);
          }
      	// 判断两个日期相差的时长
          public static long between(Date beginDate, Date endDate, DateUnit unit, boolean isAbs) {
              return (new DateBetween(beginDate, endDate, isAbs)).between(unit);
          }
      	// 判断两个日期相差的毫秒数
          public static long betweenMs(Date beginDate, Date endDate) {
              return (new DateBetween(beginDate, endDate)).between(DateUnit.MS);
          }
      	// 判断两个日期相差的天数
          public static long betweenDay(Date beginDate, Date endDate, boolean isReset) {
              if (isReset) {
                  beginDate = beginOfDay((Date)beginDate);
                  endDate = beginOfDay((Date)endDate);
              }
      
              return between((Date)beginDate, (Date)endDate, DateUnit.DAY);
          }
      	// 计算指定指定时间区间内的周数
          public static long betweenWeek(Date beginDate, Date endDate, boolean isReset) {
              if (isReset) {
                  beginDate = beginOfDay((Date)beginDate);
                  endDate = beginOfDay((Date)endDate);
              }
      
              return between((Date)beginDate, (Date)endDate, DateUnit.WEEK);
          }
      	// 计算两个日期相差月数在非重置情况下,如果起始日期的天大于结束日期的天,月数要少算1(不足1个月)
          public static long betweenMonth(Date beginDate, Date endDate, boolean isReset) {
              return (new DateBetween(beginDate, endDate)).betweenMonth(isReset);
          }
      	// 计算两个日期相差年数在非重置情况下,如果起始日期的月大于结束日期的月,年数要少算1(不足1年)
          public static long betweenYear(Date beginDate, Date endDate, boolean isReset) {
              return (new DateBetween(beginDate, endDate)).betweenYear(isReset);
          }
      	// 格式化日期间隔输出
          public static String formatBetween(Date beginDate, Date endDate, Level level) {
              return formatBetween(between(beginDate, endDate, DateUnit.MS), level);
          }
      	// 格式化日期间隔输出,精确到毫秒
          public static String formatBetween(Date beginDate, Date endDate) {
              return formatBetween(between(beginDate, endDate, DateUnit.MS));
          }
      	// 格式化日期间隔输出
          public static String formatBetween(long betweenMs, Level level) {
              return (new BetweenFormatter(betweenMs, level)).format();
          }
      	// 格式化日期间隔输出,精确到毫秒
          public static String formatBetween(long betweenMs) {
              return (new BetweenFormatter(betweenMs, Level.MILLISECOND)).format();
          }
      	// 当前日期是否在日期指定范围内 起始日期和结束日期可以互换
          public static boolean isIn(Date date, Date beginDate, Date endDate) {
              return date instanceof DateTime ? ((DateTime)date).isIn(beginDate, endDate) : (new DateTime(date)).isIn(beginDate, endDate);
          }
      	// 是否为相同时间 此方法比较两个日期的时间戳是否相同
          public static boolean isSameTime(Date date1, Date date2) {
              return date1.compareTo(date2) == 0;
          }
      	// 比较两个日期是否为同一天
          public static boolean isSameDay(Date date1, Date date2) {
              if (date1 != null && date2 != null) {
                  return CalendarUtil.isSameDay(calendar(date1), calendar(date2));
              } else {
                  throw new IllegalArgumentException("The date must not be null");
              }
          }
      	// 比较两个日期是否为同一周
          public static boolean isSameWeek(Date date1, Date date2, boolean isMon) {
              if (date1 != null && date2 != null) {
                  return CalendarUtil.isSameWeek(calendar(date1), calendar(date2), isMon);
              } else {
                  throw new IllegalArgumentException("The date must not be null");
              }
          }
      	// 比较两个日期是否为同一月
          public static boolean isSameMonth(Date date1, Date date2) {
              if (date1 != null && date2 != null) {
                  return CalendarUtil.isSameMonth(calendar(date1), calendar(date2));
              } else {
                  throw new IllegalArgumentException("The date must not be null");
              }
          }
      	// 计时,常用于记录某段代码的执行时间,单位:纳秒
          public static long spendNt(long preTime) {
              return System.nanoTime() - preTime;
          }
      	// 计时,常用于记录某段代码的执行时间,单位:毫秒
          public static long spendMs(long preTime) {
              return System.currentTimeMillis() - preTime;
          }
      	// 格式化成yyMMddHHmm后转换为int型(过期)
          /** @deprecated */
          @Deprecated
          public static int toIntSecond(Date date) {
              return Integer.parseInt(format(date, "yyMMddHHmm"));
          }
      	// 计时器 计算某个过程花费的时间,精确到毫秒
          public static TimeInterval timer() {
              return new TimeInterval();
          }
      	// 计时器 计算某个过程花费的时间,精确到毫秒
          public static TimeInterval timer(boolean isNano) {
              return new TimeInterval(isNano);
          }
      	// 计时器 创建秒表{@link StopWatch},用于对代码块的执行时间计数
          public static StopWatch createStopWatch() {
              return new StopWatch();
          }
      	// 计时器 创建秒表{@link StopWatch},用于对代码块的执行时间计数
          public static StopWatch createStopWatch(String id) {
              return new StopWatch(id);
          }
      	// 生日转为年龄,计算法定年龄
          public static int ageOfNow(String birthDay) {
              return ageOfNow((Date)parse(birthDay));
          }
      	// 生日转为年龄,计算法定年龄
          public static int ageOfNow(Date birthDay) {
              return age(birthDay, date());
          }
      	// 是否闰年
          public static boolean isLeapYear(int year) {
              return Year.isLeap((long)year);
          }
      	// 计算相对于dateToCompare的年龄,长用于计算指定生日在某年的年龄
          public static int age(Date birthday, Date dateToCompare) {
              Assert.notNull(birthday, "Birthday can not be null !", new Object[0]);
              if (null == dateToCompare) {
                  dateToCompare = date();
              }
      
              return age(birthday.getTime(), ((Date)dateToCompare).getTime());
          }
      	// 是否过期
          /** @deprecated */
          @Deprecated
          public static boolean isExpired(Date startDate, DateField dateField, int timeLength, Date endDate) {
              Date offsetDate = offset(startDate, dateField, timeLength);
              return offsetDate.after(endDate);
          }
      	// 是否过期
          /** @deprecated */
          @Deprecated
          public static boolean isExpired(Date startDate, Date endDate, Date checkDate) {
              return betweenMs(startDate, checkDate) > betweenMs(startDate, endDate);
          }
      	// HH:mm:ss 时间格式字符串转为秒数
          public static int timeToSecond(String timeStr) {
              if (StrUtil.isEmpty(timeStr)) {
                  return 0;
              } else {
                  List<String> hms = StrUtil.splitTrim(timeStr, ':', 3);
                  int lastIndex = hms.size() - 1;
                  int result = 0;
      
                  for(int i = lastIndex; i >= 0; --i) {
                      result = (int)((double)result + (double)Integer.parseInt((String)hms.get(i)) * Math.pow(60.0D, (double)(lastIndex - i)));
                  }
      
                  return result;
              }
          }
      	// 秒数转为时间格式(HH:mm:ss)
          public static String secondToTime(int seconds) {
              if (seconds < 0) {
                  throw new IllegalArgumentException("Seconds must be a positive number!");
              } else {
                  int hour = seconds / 3600;
                  int other = seconds % 3600;
                  int minute = other / 60;
                  int second = other % 60;
                  StringBuilder sb = new StringBuilder();
                  if (hour < 10) {
                      sb.append("0");
                  }
      
                  sb.append(hour);
                  sb.append(":");
                  if (minute < 10) {
                      sb.append("0");
                  }
      
                  sb.append(minute);
                  sb.append(":");
                  if (second < 10) {
                      sb.append("0");
                  }
      
                  sb.append(second);
                  return sb.toString();
              }
          }
      	// 创建日期范围生成器
          public static DateRange range(Date start, Date end, DateField unit) {
              return new DateRange(start, end, unit);
          }
      	// 创建日期范围内数组
          public static List<DateTime> rangeContains(DateRange start, DateRange end) {
              List<DateTime> startDateTimes = CollUtil.newArrayList(start);
              List<DateTime> endDateTimes = CollUtil.newArrayList(end);
              Stream var10000 = startDateTimes.stream();
              endDateTimes.getClass();
              return (List)var10000.filter(endDateTimes::contains).collect(Collectors.toList());
          }
      	// 创建日期范围外数组
          public static List<DateTime> rangeNotContains(DateRange start, DateRange end) {
              List<DateTime> startDateTimes = CollUtil.newArrayList(start);
              List<DateTime> endDateTimes = CollUtil.newArrayList(end);
              return (List)endDateTimes.stream().filter((item) -> {
                  return !startDateTimes.contains(item);
              }).collect(Collectors.toList());
          }
      	// 创建日期范围自定义返回数组
          public static <T> List<T> rangeFunc(Date start, Date end, DateField unit, Function<Date, T> func) {
              if (start != null && end != null && !start.after(end)) {
                  ArrayList<T> list = new ArrayList();
                  Iterator var5 = range(start, end, unit).iterator();
      
                  while(var5.hasNext()) {
                      DateTime date = (DateTime)var5.next();
                      list.add(func.apply(date));
                  }
      
                  return list;
              } else {
                  return Collections.emptyList();
              }
          }
      	// 创建日期范围消费后返回数组
          public static void rangeConsume(Date start, Date end, DateField unit, Consumer<Date> consumer) {
              if (start != null && end != null && !start.after(end)) {
                  range(start, end, unit).forEach(consumer);
              }
          }
      	// 将时间范围按照总痕步长划分成时间段
          public static List<DateTime> rangeToList(Date start, Date end, DateField unit) {
              return CollUtil.newArrayList(range(start, end, unit));
          }
      	// 将时间范围按照总痕步长划分成时间段 (扩大倍数)
          public static List<DateTime> rangeToList(Date start, Date end, DateField unit, int step) {
              return CollUtil.newArrayList(new DateRange(start, end, unit, step));
          }
      	// 将时间范围按照总痕步长划分成时间段 (扩大倍数)
          public static String getZodiac(int month, int day) {
              return Zodiac.getZodiac(month, day);
          }
      	// 获取中文星座
          public static String getChineseZodiac(int year) {
              return Zodiac.getChineseZodiac(year);
          }
      	// 比较大小 (返回数字 0平等 -1 小于 1 大于)
          public static int compare(Date date1, Date date2) {
              return CompareUtil.compare(date1, date2);
          }
      	// 日期格式化比较大小 (返回数字 0平等 -1 小于 1 大于)
          public static int compare(Date date1, Date date2, String format) {
              if (format != null) {
                  if (date1 != null) {
                      date1 = parse((CharSequence)format((Date)date1, (String)format), (String)format);
                  }
      
                  if (date2 != null) {
                      date2 = parse((CharSequence)format((Date)date2, (String)format), (String)format);
                  }
              }
      
              return CompareUtil.compare((Comparable)date1, (Comparable)date2);
          }
      	// 纳秒转毫秒
          public static long nanosToMillis(long duration) {
              return TimeUnit.NANOSECONDS.toMillis(duration);
          }
      	// 纳秒转秒
          public static double nanosToSeconds(long duration) {
              return (double)duration / 1.0E9D;
          }
      	// Date对象转换为{@link Instant}对象
          public static Instant toInstant(Date date) {
              return null == date ? null : date.toInstant();
          }
      	// Date对象转换为{@link Instant}对象
          public static Instant toInstant(TemporalAccessor temporalAccessor) {
              return TemporalAccessorUtil.toInstant(temporalAccessor);
          }
      	// {@link Instant} 转换为 {@link LocalDateTime},使用系统默认时区
          public static LocalDateTime toLocalDateTime(Instant instant) {
              return LocalDateTimeUtil.of(instant);
          }
      	// {@link Date} 转换为 {@link LocalDateTime},使用系统默认时区
          public static LocalDateTime toLocalDateTime(Date date) {
              return LocalDateTimeUtil.of(date);
          }
      	// 转换时区
          public static DateTime convertTimeZone(Date date, ZoneId zoneId) {
              return new DateTime(date, ZoneUtil.toTimeZone(zoneId));
          }
      	// 转换时区
          public static DateTime convertTimeZone(Date date, TimeZone timeZone) {
              return new DateTime(date, timeZone);
          }
      	// 获取某年多少天
          public static int lengthOfYear(int year) {
              return Year.of(year).length();
          }
      	// 获取某月多少天 (是闰年嘛)
          public static int lengthOfMonth(int month, boolean isLeapYear) {
              return java.time.Month.of(month).length(isLeapYear);
          }
      	// 时间格式化
          public static SimpleDateFormat newSimpleFormat(String pattern) {
              return newSimpleFormat(pattern, (Locale)null, (TimeZone)null);
          }
      	// 时间格式化
          public static SimpleDateFormat newSimpleFormat(String pattern, Locale locale, TimeZone timeZone) {
              if (null == locale) {
                  locale = Locale.getDefault(Category.FORMAT);
              }
      
              SimpleDateFormat format = new SimpleDateFormat(pattern, locale);
              if (null != timeZone) {
                  format.setTimeZone(timeZone);
              }
      
              format.setLenient(false);
              return format;
          }
          // 判断时间类型是什么
          public static String getShotName(TimeUnit unit) {
              switch(unit) {
              case NANOSECONDS:
                  return "ns";
              case MICROSECONDS:
                  return "μs";
              case MILLISECONDS:
                  return "ms";
              case SECONDS:
                  return "s";
              case MINUTES:
                  return "min";
              case HOURS:
                  return "h";
              default:
                  return unit.name().toLowerCase();
              }
          }
      	// 时间是否重叠
          public static boolean isOverlap(Date realStartTime, Date realEndTime, Date startTime, Date endTime) {
              return realStartTime.compareTo(endTime) <= 0 && startTime.compareTo(realEndTime) <= 0;
          }
      	// 当前时间是否是最后一天
          public static boolean isLastDayOfMonth(Date date) {
              return date(date).isLastDayOfMonth();
          }
      	// 获取某月最后一天
          public static int getLastDayOfMonth(Date date) {
              return date(date).getLastDayOfMonth();
          }
      
          private static String normalize(CharSequence dateStr) {
              if (StrUtil.isBlank(dateStr)) {
                  return StrUtil.str(dateStr);
              } else {
                  List<String> dateAndTime = StrUtil.splitTrim(dateStr, ' ');
                  int size = dateAndTime.size();
                  if (size >= 1 && size <= 2) {
                      StringBuilder builder = StrUtil.builder();
                      String datePart = ((String)dateAndTime.get(0)).replaceAll("[/.年月]", "-");
                      datePart = StrUtil.removeSuffix(datePart, "日");
                      builder.append(datePart);
                      if (size == 2) {
                          builder.append(' ');
                          String timePart = ((String)dateAndTime.get(1)).replaceAll("[时分秒]", ":");
                          timePart = StrUtil.removeSuffix(timePart, ":");
                          timePart = timePart.replace(',', '.');
                          builder.append(timePart);
                      }
      
                      return builder.toString();
                  } else {
                      return StrUtil.str(dateStr);
                  }
              }
          }
      }
      
      
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不脱顶的程序员小王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值