package com.gunshi.project.xyt.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; /** * Description: * Created by wanyan on 2024/2/28 * * @author wanyan * @version 1.0 */ public class DateUtil { // 使用 ConcurrentMap 来缓存 SimpleDateFormat 实例 private static final ConcurrentMap> DATE_FORMAT_CACHE = new ConcurrentHashMap<>(); private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); private static SimpleDateFormat chineseYmd = new SimpleDateFormat("yyyy年MM月dd日"); private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); private static DateTimeFormatter ymdformat = DateTimeFormatter.ofPattern("yyyy-MM-dd"); private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd日HH时"); private static DateTimeFormatter ym = DateTimeFormatter.ofPattern("YYYYMM"); public static Date convertStringToDate(String str){ try { return df.parse(str); } catch (ParseException e) { throw new RuntimeException(e); } } public static final ThreadLocal sdfhmsS = new ThreadLocal() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); } }; public static String convertDateToString(Date date){ return sdf.format(date); } public static String convertDateToMDSString(Date date){ return df.format(date); } public static String convertDateToChineseYmd(Date date){ return chineseYmd.format(date); } public static long hoursBetweenDate(Date start,Date end){ long startTime = start.getTime(); long endTime = end.getTime(); long hours = TimeUnit.MILLISECONDS.toHours(endTime - startTime); return Math.round(hours); } /** * 年初 * @param year * @return */ public static LocalDateTime beginningOfYear(Integer year){ return LocalDateTime.of(year, 1, 1, 0, 0, 0, 0); } /** * 年末 * @param year * @return */ public static LocalDateTime endOfYear(Integer year){ return beginningOfYear(year).plusYears(1).minusSeconds(1); } /** * 年初 * @param year * @return */ public static Date beginOfYearToDate(Integer year){ if (year == null) { throw new IllegalArgumentException("Year cannot be null"); } LocalDate localDate = LocalDate.of(year, 1, 1); return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); } /** * 年末 * @param year * @return */ public static Date endOfYearToDate(Integer year){ if (year == null) { throw new IllegalArgumentException("Year cannot be null"); } LocalDateTime time = LocalDateTime.of(year, 1, 1, 0, 0, 0, 0); time = time.plusYears(1).minusSeconds(1); return Date.from(time.atZone(ZoneId.systemDefault()).toInstant()); } /** * 将Date对象转换为LocalDateTime对象. * * @param date 需要转换的Date对象 * @return 转换后的LocalDateTime对象 */ public static Optional convertFromDate(Date date) { if (date == null) { throw new IllegalArgumentException("date is null"); } Instant instant = date.toInstant(); return Optional.of(instant.atZone(ZoneId.systemDefault()).toLocalDateTime()); } public static String getIntegerTime(){ LocalDateTime now = LocalDateTime.now(); LocalDateTime roundedTime = now.withMinute(0).withSecond(0).withNano(0); return roundedTime.format(formatter); } public static String getMinusIntegerTime(){ LocalDateTime yesterday = LocalDateTime.now().minusDays(1); LocalDateTime roundedTime = yesterday.withMinute(0).withSecond(0).withNano(0); return roundedTime.format(formatter); } public static String convertDH(String str){ LocalDateTime dateTime = LocalDateTime.parse(str, formatter); return dateTime.format(dtf); } public static String getMinusTime(String str,long hour){ LocalDateTime dateTime = LocalDateTime.parse(str, formatter); LocalDateTime minusTime = dateTime.minusHours(hour); return minusTime.format(formatter); } public static String getPlusTime(String str,long hour){ LocalDateTime dateTime = LocalDateTime.parse(str, formatter); LocalDateTime plusTime = dateTime.plusHours(hour); return plusTime.format(formatter); } public static String getPlusDate(Date date,long day){ String str = convertDateToString(date); LocalDate localDate = LocalDate.parse(str, ymdformat); LocalDate plusDay = localDate.plusDays(day); return plusDay.format(ymdformat); } public static String getTodayEight(){ LocalDateTime now = LocalDateTime.now(); LocalDateTime roundedTime = now.withHour(8).withMinute(0).withSecond(0).withNano(0); return roundedTime.format(formatter); } public static Integer getMD(int year, int month) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (month == 2) { //判断是否是闰年 if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { return 29; } else { return 28; } } return 31; } public static String getYM() { LocalDateTime now = LocalDateTime.now(); return now.format(ym); } public static List getDatesBetween(Date startDate, Date endDate,Boolean isDesc) { List dates = new ArrayList<>(); Calendar calendar = Calendar.getInstance(); while (startDate.getTime()<=endDate.getTime()){ // 把日期添加到集合 dates.add(convertDateToString(startDate)); // 设置日期 calendar.setTime(startDate); //把日期增加一天 calendar.add(Calendar.DATE, 1); // 获取增加后的日期 startDate=calendar.getTime(); } if(isDesc){ return dates.reversed(); } return dates; } public static List getDatesBetween(Date startDate, Date endDate) { List dates = new ArrayList<>(); Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); while (calendar.getTime().before(endDate)) { dates.add(calendar.getTime()); calendar.add(Calendar.DATE, 1); } dates.add(endDate); return dates; } public static boolean isValidDate(Date date, String format) { if (date == null || format == null || format.isEmpty()) { return false; } try { SimpleDateFormat sdf = getThreadSafeFormatter(format); sdf.setLenient(false); // 设置严格模式 sdf.parse(date.toString()); return true; } catch (IllegalArgumentException | ParseException e) { return false; } } private static SimpleDateFormat getThreadSafeFormatter(String format) { return DATE_FORMAT_CACHE.computeIfAbsent(format, key -> ThreadLocal.withInitial(() -> new SimpleDateFormat(key))).get(); } }