package com.mh.common.utils; import java.lang.management.ManagementFactory; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; import java.util.Calendar; import java.util.Date; import com.mh.common.core.domain.vo.EnergyConsumptionVO; import com.mh.common.core.domain.vo.EnergyQueryVO; import org.apache.commons.lang3.time.DateFormatUtils; /** * 时间工具类 * * @author mh */ public class DateUtils extends org.apache.commons.lang3.time.DateUtils { public static String YYYY = "yyyy"; public static String YYYY_MM = "yyyy-MM"; public static String YYYY_MM_DD = "yyyy-MM-dd"; public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}; /** * 将 Date 类型的 curTime 转换为 LocalTime * * @param curTime 需要转换的 Date 对象 * @return 转换后的 LocalTime 对象 */ public static LocalTime convertDateToLocalTime(Date curTime) { // 将 Date 转换为 Instant java.time.Instant instant = curTime.toInstant(); // 获取系统默认时区,或者指定其他时区,例如 ZoneId.of("UTC") ZoneId zone = ZoneId.systemDefault(); // 将 Instant 转换为 LocalTime return instant.atZone(zone).toLocalTime(); } public static boolean isCurrentTimeInRange(Date startTimeStr, Date endTimeStr, Date curTime) { LocalTime startTime = convertDateToLocalTime(startTimeStr); LocalTime endTime = convertDateToLocalTime(endTimeStr); LocalTime currentTime = convertDateToLocalTime(curTime); if (startTime.equals(endTime)) { // 开始和结束时间相同,视为全天范围内 return true; } else if (endTime.isAfter(startTime)) { // 时间段不跨天,判断当前时间是否在[startTime, endTime]区间内 return !currentTime.isBefore(startTime) && !currentTime.isAfter(endTime); } else { // 时间段跨天,判断当前时间是否在[startTime, 23:59:59.999999999]或[00:00:00, endTime] return !currentTime.isBefore(startTime) || !currentTime.isAfter(endTime); } } /** * 获取当前Date型日期 * * @return Date() 当前日期 */ public static Date getNowDate() { return new Date(); } /** * 获取当前日期, 默认格式为yyyy-MM-dd * * @return String */ public static String getDate() { return dateTimeNow(YYYY_MM_DD); } public static final String getTime() { return dateTimeNow(YYYY_MM_DD_HH_MM_SS); } public static final String dateTimeNow() { return dateTimeNow(YYYYMMDDHHMMSS); } public static final String dateTimeNow(final String format) { return parseDateToStr(format, new Date()); } public static final String dateTime(final Date date) { return parseDateToStr(YYYY_MM_DD, date); } public static final String parseDateToStr(final String format, final Date date) { return new SimpleDateFormat(format).format(date); } public static final Date dateTime(final String format, final String ts) { try { return new SimpleDateFormat(format).parse(ts); } catch (ParseException e) { throw new RuntimeException(e); } } /** * 日期路径 即年/月/日 如2018/08/08 */ public static final String datePath() { Date now = new Date(); return DateFormatUtils.format(now, "yyyy/MM/dd"); } /** * 日期路径 即年/月/日 如20180808 */ public static final String dateTime() { Date now = new Date(); return DateFormatUtils.format(now, "yyyyMMdd"); } /** * 日期型字符串转化为日期 格式 */ public static Date parseDate(Object str) { if (str == null) { return null; } try { return parseDate(str.toString(), parsePatterns); } catch (ParseException e) { return null; } } /** * 获取服务器启动时间 */ public static Date getServerStartDate() { long time = ManagementFactory.getRuntimeMXBean().getStartTime(); return new Date(time); } /** * 计算相差天数 */ public static int differentDaysByMillisecond(Date date1, Date date2) { return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24))); } /** * 计算时间差 * * @param endDate 最后时间 * @param startTime 开始时间 * @return 时间差(天/小时/分钟) */ public static String timeDistance(Date endDate, Date startTime) { long nd = 1000 * 24 * 60 * 60; long nh = 1000 * 60 * 60; long nm = 1000 * 60; // long ns = 1000; // 获得两个时间的毫秒时间差异 long diff = endDate.getTime() - startTime.getTime(); // 计算差多少天 long day = diff / nd; // 计算差多少小时 long hour = diff % nd / nh; // 计算差多少分钟 long min = diff % nd % nh / nm; // 计算差多少秒//输出结果 // long sec = diff % nd % nh % nm / ns; return day + "天" + hour + "小时" + min + "分钟"; } /** * 增加 LocalDateTime ==> Date */ public static Date toDate(LocalDateTime temporalAccessor) { ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault()); return Date.from(zdt.toInstant()); } /** * 增加 LocalDate ==> Date */ public static Date toDate(LocalDate temporalAccessor) { LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0)); ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault()); return Date.from(zdt.toInstant()); } /* * 获取同一个时间的上一个时间 * @param timerStr * @return */ public static String yoyDate(String timerStr) { DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); DateTimeFormatter timeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate localDate = LocalDate.parse(timerStr, timeFormatter); LocalDate localDate1 = localDate.minusYears(1); return localDate1.format(timeFormatter1).concat(timerStr.substring(10)); } /** * 获取同一个时间的上一个时间 * @param timerStr * @return */ public static String momDate(String timerStr, String timeType, String timeRange) { DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime localDate = LocalDateTime.parse(timerStr, timeFormatter); LocalDateTime localDate1 = null; switch (timeType) { case "hour": localDate1 = localDate.minusHours(1); break; case "day": localDate1 = localDate.minusDays(1); break; case "month": if ("end".equals(timeRange)) { localDate1 = localDate.minusMonths(1).with(TemporalAdjusters.lastDayOfMonth()); } else if ("start".equals(timeRange)) { localDate1 = localDate.minusMonths(1).with(TemporalAdjusters.firstDayOfMonth()); } break; case "year": localDate1 = localDate.minusYears(1); break; } assert localDate1 != null; return localDate1.format(timeFormatter); } public static void energyDateChange(EnergyConsumptionVO vo) { switch (vo.getTimeType()) { case "day": vo.setStartTime(vo.getStartTime().concat(" 00:00:00")); vo.setEndTime(vo.getEndTime().concat(" 23:59:59")); break; case "month": YearMonth yearMonth = YearMonth.parse(vo.getStartTime(), DateTimeFormatter.ofPattern("yyyy-MM")); LocalDate firstDayOfMonth = yearMonth.atDay(1); String firstDayOutput = firstDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); vo.setStartTime(firstDayOutput.concat(" 00:00:00")); YearMonth yearMonth1 = YearMonth.parse(vo.getEndTime(), DateTimeFormatter.ofPattern("yyyy-MM")); LocalDate firstDayOfMonth1 = yearMonth1.atEndOfMonth(); String firstDayOutput1 = firstDayOfMonth1.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); vo.setEndTime(firstDayOutput1.concat(" 23:59:59")); break; case "year": vo.setStartTime(vo.getStartTime().concat("-01-01 00:00:00")); vo.setEndTime(vo.getEndTime().concat("-12-31 23:59:59")); break; default: break; } } public static void sysEnergyDateChange(EnergyQueryVO vo) { switch (vo.getTimeType()) { case "day": vo.setStartTime(vo.getStartTime().concat(" 00:00:00")); vo.setEndTime(vo.getEndTime().concat(" 23:59:59")); break; case "month": YearMonth yearMonth = YearMonth.parse(vo.getStartTime(), DateTimeFormatter.ofPattern("yyyy-MM")); LocalDate firstDayOfMonth = yearMonth.atDay(1); String firstDayOutput = firstDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); vo.setStartTime(firstDayOutput.concat(" 00:00:00")); YearMonth yearMonth1 = YearMonth.parse(vo.getEndTime(), DateTimeFormatter.ofPattern("yyyy-MM")); LocalDate firstDayOfMonth1 = yearMonth1.atEndOfMonth(); String firstDayOutput1 = firstDayOfMonth1.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); vo.setEndTime(firstDayOutput1.concat(" 23:59:59")); break; case "year": vo.setStartTime(vo.getStartTime().concat("-01-01 00:00:00")); vo.setEndTime(vo.getEndTime().concat("-12-31 23:59:59")); break; default: break; } } /** * 计算时间差 * @param curTime * @param lastTime * @param type * @return */ public static BigDecimal calcDate(Object curTime, Object lastTime, String type) { String momDate = momDate((String) curTime, type, ""); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); long curDateMillis = 0; long lastTimeMillis = 0; try { LocalDateTime dateTime = LocalDateTime.parse(momDate, formatter); curDateMillis = dateTime.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond(); LocalDateTime lastDateTime = LocalDateTime.parse((CharSequence) lastTime, formatter); lastTimeMillis = lastDateTime.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond(); } catch (Exception e) { System.err.println("无法解析时间字符串: " + e.getMessage()); } return (new BigDecimal(curDateMillis - lastTimeMillis)).divide(new BigDecimal(60),2, RoundingMode.HALF_UP); } public static String getTimeLen(String timeType) { String timeLen = ""; switch (timeType) { case "hour": timeLen = "13"; break; case "day": timeLen = "10"; break; case "month": timeLen = "7"; break; case "year": timeLen = "4"; break; } return timeLen; } /** * 把日期格式化为字符串 * * @param date 日期 * @param format 格式 * @return 返回格式化之后的字符串 */ public static Date stringToDate(String date, String format) { SimpleDateFormat dateFormat = new SimpleDateFormat(format); try { return dateFormat.parse(date); } catch (ParseException e) { return null; } } /** * 获取每隔多少分钟的格式化时间 * 传入 date "2023-07-31 16:23:00" minuteInter 5分钟 * 返回 "2023-07-31 16:20:00" 整点 * * @param date 时间 * @param minuteInterval 间隔 * @return 时间 */ public static String getTimeMin(Date date, int minuteInterval) { if (minuteInterval <= 0 || minuteInterval > 30) { throw new RuntimeException("minute参数错误"); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = null; format = sdf.format(date); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int minute = calendar.get(Calendar.MINUTE); int num = minute / minuteInterval; String curDate = format.substring(0, 13) + ":" + (num * minuteInterval) + ":00"; // System.out.println("curDate = " + curDate); return curDate; } /** * 把日期格式化为字符串 * * @param date 日期 * @param format 格式 * @return 返回格式化之后的字符串 */ public static String dateToString(Date date, String format) { SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(date); } /** * 时间格式转 yyyy-MM-dd'T'HH:mm:ssZ * @return */ public static String dateToTsStr() { // 获取当前时间 Instant now = Instant.now(); // 转换为ZonedDateTime并设置时区为UTC ZonedDateTime zonedDateTime = now.atZone(ZoneId.of("UTC")); // 创建DateTimeFormatter对象并设置格式 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"); // 格式化日期 return zonedDateTime.format(formatter); } }