java 工具类日期工具类

发布时间 2023-05-05 10:56:49作者: 海的味道

1.DateTimeHelper.java

package cn.togeek.util;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;

import cn.togeek.enums.DateType;

import java.nio.charset.Charset;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class DateTimeHelper {
   public static final String DATE_PATTERN = "yyyy-MM-dd";
   public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_PATTERN);

   public static final String DATE_STR_PATTERN = "yyyy年MM月dd日";

   public static final DateTimeFormatter DATE_STR_FORMATTER = DateTimeFormatter.ofPattern(DATE_STR_PATTERN);

   public static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
   public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern(DATETIME_PATTERN);

   public static final String DATETIME_96_PATTERN = "MMdd HH:mm";

   public static final DateTimeFormatter DATETIME_96_FORMATTER = DateTimeFormatter.ofPattern(DATETIME_96_PATTERN);

   public static final String TIME_HM_PATTERN = "HH:mm";

   public static final DateTimeFormatter DATETIME_96_TIME_FORMATTER = DateTimeFormatter.ofPattern(TIME_HM_PATTERN);

   public static final DateTimeFormatter TIME_HM_FORMATTER = DateTimeFormatter.ofPattern(TIME_HM_PATTERN);

   public static final String DATE_96_PATTERN = "MMdd ";

   public static final DateTimeFormatter DATE_96_FORMATTER = DateTimeFormatter.ofPattern(DATE_96_PATTERN);

   public static final String MONTH_DAY_PATTERN = "MM月dd日 ";

   public static final DateTimeFormatter MONTH_DAY_FORMATTER = DateTimeFormatter.ofPattern(MONTH_DAY_PATTERN);

   public static final String END_TIME_STR = "24:00";

   private static final Map<String, DateTimeFormatter> formatters = new HashMap<>();

   static {
      formatters.put(DATE_PATTERN, DATE_FORMATTER);
      formatters.put(DATETIME_PATTERN, DATETIME_FORMATTER);
   }

   private DateTimeHelper() {
   }

   public static LocalDate date2LocalDate(Date date) {
      Instant instant = date.toInstant();
      ZoneId zoneId = ZoneId.systemDefault();
      return instant.atZone(zoneId).toLocalDate();
   }

   public static LocalDateTime date2LocalDateTime(Date date) {
      Instant instant = date.toInstant();
      ZoneId zoneId = ZoneId.systemDefault();
      return instant.atZone(zoneId).toLocalDateTime();
   }

   public static LocalDateTime text2LocalDateTime(String timeText) {
      return text2LocalDateTime(timeText, null);
   }

   public static LocalDateTime text2LocalDateTime(String timeText, String pattern) {
      pattern = pattern == null ? DATETIME_PATTERN : pattern;
      if(formatters.get(pattern) == null) {
         formatters.put(pattern, DateTimeFormatter.ofPattern(pattern));
      }

      return LocalDateTime.parse(timeText, formatters.get(pattern));
   }

   public static String localDateTime2Text(LocalDateTime dateTime) {
      return localDateTime2Text(dateTime, null);
   }

   public static String localDateTime2Text(LocalDateTime dateTime, String pattern) {
      pattern = pattern == null ? DATETIME_PATTERN : pattern;
      if(formatters.get(pattern) == null) {
         formatters.put(pattern, DateTimeFormatter.ofPattern(pattern));
      }

      return formatters.get(pattern).format(dateTime);
   }

   public static LocalDate text2LocalDate(String dateText) {
      return text2LocalDate(dateText, null);
   }

   public static LocalDate text2LocalDate(String timeText, String pattern) {
      pattern = pattern == null ? DATE_PATTERN : pattern;
      if(formatters.get(pattern) == null) {
         formatters.put(pattern, DateTimeFormatter.ofPattern(pattern));
      }

      return LocalDate.parse(timeText, formatters.get(pattern));
   }

   public static String localDate2Text(LocalDate date) {
      return localDate2Text(date, null);
   }

   public static String localDate2Text(LocalDate date, String pattern) {
      pattern = pattern == null ? DATE_PATTERN : pattern;
      if(formatters.get(pattern) == null) {
         formatters.put(pattern, DateTimeFormatter.ofPattern(pattern));
      }

      return formatters.get(pattern).format(date);
   }

   public static Date localDate2Date(LocalDate localDate) {
      ZoneId zone = ZoneId.systemDefault();
      ZonedDateTime zonedDateTime = localDate.atStartOfDay(zone);
      return Date.from(zonedDateTime.toInstant());
   }

   public static Date localDateTime2Date(LocalDateTime localDateTime) {
      ZoneId zone = ZoneId.systemDefault();
      Instant instant = localDateTime.atZone(zone).toInstant();
      return Date.from(instant);
   }

   public static long localDateTime2Timestamp(LocalDateTime localDateTime) {
      ZoneId zone = ZoneId.systemDefault();
      Instant instant = localDateTime.atZone(zone).toInstant();
      return instant.toEpochMilli();
   }

   public static LocalDateTime timestamp2LocalDateTime(long timestamp) {
      Instant instant = Instant.ofEpochMilli(timestamp);
      ZoneId zone = ZoneId.systemDefault();
      return LocalDateTime.ofInstant(instant, zone);
   }

   public static LocalDateTime beginOfDay(LocalDateTime localDateTime) {
      return localDateTime.with(LocalTime.MIN);
   }

   public static LocalDateTime beginOfDay(LocalDate localDate) {
      return LocalDateTime.of(localDate, LocalTime.MIN);
   }

   public static LocalDateTime endOfDay(LocalDateTime localDateTime) {
      return localDateTime.with(LocalTime.MAX);
   }

   public static LocalDateTime endOfDay(LocalDate localDate) {
      return LocalDateTime.of(localDate, LocalTime.MAX);
   }

   public static LocalDateTime beginOfMonth(LocalDateTime localDateTime) {
      return localDateTime.with(TemporalAdjusters.firstDayOfMonth()).with(LocalDateTime.MIN);
   }

   public static LocalDateTime beginOfMonth(LocalDate localDate) {
      return LocalDateTime.of(localDate.with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN);
   }

   public static LocalDateTime endOfMonth(LocalDateTime localDateTime) {
      return localDateTime.with(TemporalAdjusters.lastDayOfMonth()).with(LocalDateTime.MAX);
   }

   public static LocalDateTime endOfMonth(LocalDate localDate) {
      return LocalDateTime.of(localDate.with(TemporalAdjusters.lastDayOfMonth()), LocalTime.MAX);
   }

   public static LocalDateTime beginOfYear(LocalDateTime localDateTime) {
      return localDateTime.with(TemporalAdjusters.firstDayOfYear()).with(LocalDateTime.MIN);
   }

   public static LocalDateTime beginOfYear(LocalDate localDate) {
      return LocalDateTime.of(localDate.with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN);
   }

   public static LocalDateTime endOfYear(LocalDateTime localDateTime) {
      return localDateTime.with(TemporalAdjusters.lastDayOfYear()).with(LocalDateTime.MAX);
   }

   public static LocalDateTime endOfYear(LocalDate localDate) {
      return LocalDateTime.of(localDate.with(TemporalAdjusters.lastDayOfYear()), LocalTime.MAX);
   }

   public static LocalDate firstDayOfMonth(LocalDate localDate) {
      return localDate.with(TemporalAdjusters.firstDayOfMonth());
   }

   public static LocalDate lastDayOfMonth(LocalDate localDate) {
      return localDate.with(TemporalAdjusters.lastDayOfMonth());
   }

   public static LocalDate firstDayOfYear(LocalDate localDate) {
      return localDate.with(TemporalAdjusters.firstDayOfYear());
   }

   public static LocalDate lastDayOfYear(LocalDate localDate) {
      return localDate.with(TemporalAdjusters.lastDayOfYear());
   }


   public static List<LocalDate> getDateList(LocalDate beginDate, LocalDate endDate) {
      long range = ChronoUnit.DAYS.between(beginDate, endDate) + 1;
      List<LocalDate> list = new ArrayList<>();
      for (long i = 0; i < range; i++) {
         list.add(beginDate.plusDays(i));
      }

      return list;
   }

   /**
    * 根据年月字符串获取当月第一天和最后一天
    */
   public static Map<String, LocalDate> getDateByYmstr(String date) {
      String str = date + "-01";
      LocalDate firstDay = LocalDate.parse(str, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
      LocalDate lastDate = firstDay.with(TemporalAdjusters.lastDayOfMonth());
      Map<String, LocalDate> map = new HashMap<>();
      map.put("firstDay", firstDay);
      map.put("lastDate", lastDate);
      return map;
   }

   /**
    * 获取前一天日期
    */
   public static String yesterday() {
      // 获取当前日期
      LocalDate today = LocalDate.now();
      // 获取当前日期的前一天
      return today.minusDays(1).toString();
   }

   /**
    * 获取后一天日期
    */
   public static String tomorrow() {
      // 获取当前日期
      LocalDate today = LocalDate.now();
      // 获取当前日期的前一天
      return today.plusDays(1).toString();
   }

   public static LocalDateTime strToDateTime(String dateStr, String timeStr) {
      return LocalDateTime.of(LocalDate.parse(dateStr), LocalTime.parse(timeStr));
   }

   public static String numberToTimeStr(int i) {
      return String.format("%02d:%02d", i * 15 / 60, i * 15 % 60);
   }


   public static int timeStrToNumber(String timeStr) {
      String[] split = timeStr.split(":");
      return NumberUtil.toBigInteger(split[0]).intValue() * 4 + NumberUtil.toBigInteger(split[1]).intValue() / 15;
   }

   public static LocalTime numberToLocalTime(int i) {
      try {
         return LocalTime.of(i*15/60, i*15%60);
      } catch(Exception e){
         return LocalTime.MIN;
      }

   }

   public static synchronized String fixTime(String timeStr, boolean hasSecond) {
      if (!timeStr.contains(":")) {
         throw new IllegalArgumentException("时间格式有误");
      }
      if (timeStr.contains(" ")) {
         timeStr = timeStr.split(" ")[1];
      }
      List<String> split = Arrays.stream(timeStr.split(":")).collect(Collectors.toList());
      if (!hasSecond && split.size() == 3) {
         split.remove(2);
      }
      StringBuffer time = new StringBuffer();
      for (int i = 0; i < split.size(); i++) {
         String str = split.get(i);
         String it;
         if(str.length() < 2) {
            it = "0" + str;
         }
         else {
            it = str;
         }
         time.append(it);
         if(i != split.size() - 1) {
            time.append(":");
         }
      }
      return time.toString();
   }

   public static String fixDate(String bsStr) {
      String[] fixed;
      String sepPoint = ".";
      boolean point = bsStr.contains(sepPoint);
      if (point) {
         fixed = bsStr.split("\\.");
      }
      else {
         fixed = bsStr.split("-");
      }
      String sep = point ? sepPoint : "-";
      return String.format("%s%s%02d%s%02d", fixed[0], sep, Integer.parseInt(fixed[1]), sep,
         Integer.parseInt(fixed[2]));
   }

   public static List<String> genarateTime(boolean has2400) {
      if (has2400) {
         return IntStream.rangeClosed(1, 96).mapToObj(i -> numberToTimeStr(i)).collect(Collectors.toList());
      }
      else {
         return IntStream.rangeClosed(0, 95).mapToObj(i -> numberToTimeStr(i)).collect(Collectors.toList());
      }
   }

   /***
    * 00:15-24:00
    * @param start
    * @param end
    * @param format
    * @return
    * @param <T>
    */
   public static <T> List<T> getDateList96(LocalDate start, LocalDate end, Function<LocalDateTime, T> format) {
      List<T> list = Lists.newArrayList();

      LocalDate item = start;
      while (item.isBefore(end) || item.isEqual(end)) {
         LocalTime time = LocalTime.MIN;
         for (int i = 0; i < 96; i++) {
            time = time.plusMinutes(15l);
            list.add(format.apply(LocalDateTime.of(item, time)));
         }

         item = item.plusDays(1l);
      }

      return list;
   }

   public static void main(String[] args) {
      List<LocalDateTime> dateList96 = DateTimeHelper.getDateList96(LocalDate.now(), LocalDate.now(), Function.identity());
      System.out.println(dateList96);
   }

   public static List<String> getDateList96(LocalDate start, LocalDate end) {
      return getDateList96(start, end, DEFAULT_DATE_96_FUNC);
   }

   public static final Function<LocalDateTime, String> DEFAULT_DATE_96_FUNC =
      e -> e.toLocalTime().equals(LocalTime.MIN) ? DATE_96_FORMATTER.format(e).concat(END_TIME_STR) :
         DATETIME_96_FORMATTER.format(e);

   public static List<String> getDateList96Time(LocalDate start, LocalDate end) {
      List<String> dateList96Time = getDateList96(start, end, DEFAULT_DATE_FUNC);
      return dateList96Time.stream().map(l -> {
         if ("00:00".equals(l)) {
            l = "24:00";
         }
         return l;
      }).collect(Collectors.toList());
   }

   public static final Function<LocalDateTime, String> DEFAULT_DATE_FUNC =
           e -> DATETIME_96_TIME_FORMATTER.format(e);

   public static List<String> getBetweenToTime(String startTime, String endTime) {
      int start = timeStrToNumber(startTime);
      int end = timeStrToNumber(endTime);
      return IntStream.range(start, end + 1).mapToObj(DateTimeHelper::numberToTimeStr).collect(Collectors.toList());
   }

   public static LocalDate parseLocalDate(Object date) {
      String[] parttens = {
         "yyyy-MM-dd",
         "yyyy-M-dd",
         "yyyy-M-d",
         "yyyy.MM.dd",
         "yyyy.M.dd",
         "yyyy.M.d",
         "yyyy年MM月dd日",
         "yyyy年M月dd日",
         "yyyy年M月d日",
         "yyyy/MM/dd",
         "yyyy/M/dd",
         "yyyy/M/d",
         "yyyyMMdd",
         "yyyyMdd",
         "yyyyMd",
      };
      if(date == null) {
         return null;
      }
      if(date instanceof Date) {
         return LocalDateTimeUtil.of(((Date) date)).toLocalDate();
      } else if (date instanceof String) {
         String dateStr = (String) date;
         for(String partten : parttens) {
            try {
               return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(partten));
            }
            catch(Exception e) { }
         }
      }
      return null;
   }

   public static boolean isBetween(LocalDate start, LocalDate end, LocalDate...  dates) {
      boolean ok = true;
      for(LocalDate date : dates) {
         ok &= !date.isBefore(start) && !date.isAfter(end);
      }
      return ok;
   }

   /**
    *  获取指定开始结束日期内的日期类型
    * @param begin
    * @param end
    * @return
    */
   public static Map<DateType,List<LocalDate>> getSortedDays(LocalDate begin, LocalDate end){
      Map<DateType,List<LocalDate>> dateTypeListMap = new LinkedHashMap<>();
      List<LocalDate> visited = new ArrayList<>();
      IntStream.rangeClosed(begin.getYear(), end.getYear()).forEach(year->{
         String url = "http://timor.tech/api/holiday/year/"+year;
         String result = HttpUtil.get(url, Charset.forName("UTF-8"));
         JSONObject info = JSONObject.parseObject(result);
         JSONObject holiday = info.getJSONObject("holiday");
         for(String dateStr : holiday.keySet()) {
            String fullDate = year+"-"+dateStr;
            JSONObject dateInfo = holiday.getJSONObject(dateStr);
            Boolean isHoliday = dateInfo.getBoolean("holiday");
            DateType dateType = isHoliday ? DateType.HOLIDAY : DateType.ADJUSTHOLIDAY;
            dateTypeListMap.computeIfAbsent(dateType,(s)-> new ArrayList<>());
            LocalDate date = LocalDate.parse(fullDate);
            visited.add(date);
            dateTypeListMap.get(dateType).add(date);
         }
      });
      while(!begin.isAfter(end)) {
         if(!visited.contains(begin)) {
            DayOfWeek dayOfWeek = begin.getDayOfWeek();
            DateType dateType;
            switch(dayOfWeek) {
               case SATURDAY:
                  dateType = DateType.SATURDAY;
                  break ;
               case SUNDAY:
                  dateType = DateType.SUNDAY;
                  break ;
               default:
                  dateType = DateType.WORKINGDAY;
                  break;
            }
            dateTypeListMap.computeIfAbsent(dateType,(s)-> new ArrayList<>());
            dateTypeListMap.get(dateType).add(begin);
         }
         begin = begin.plusDays(1);
      }

      return dateTypeListMap;
   }
}

2.DateType.java

package cn.togeek.enums;

/**
 * 日期类型:周六,周日,工作日,法定节假日,调休节假日
 */
public enum DateType {
   SATURDAY("周六"),
   SUNDAY("周日"),
   WORKINGDAY("工作日"),
   HOLIDAY("工作日"),
   ADJUSTHOLIDAY("调休节假日");

   DateType(String typeName) {
      this.typeName = typeName;
   }

   private String typeName;

   public String getTypeName() {
      return typeName;
   }

   public static DateType getDataTypeByName(String typeName) {
      for(DateType dateType : DateType.values()) {
         if(dateType.getTypeName().equals(typeName)) {
            return dateType;
         }
      }
      return null;
   }

}