本文主要是介绍【时间】常见-时间处理函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. 仅比较:月-日
/*** 判断时间是否在指定的起始和结束时间之间(包含边界)。** @param startTime 起始时间字符串(格式为"MM-dd")* @param endTime 结束时间字符串(格式为"MM-dd")* @param time 需要判断的时间* @return 如果时间在范围内返回true,否则返回false*/public static boolean isTimeBetween(String startTime, String endTime, LocalDateTime time) {// 定义日期格式器,仅解析月和日DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");// 将LocalDateTime转换为LocalDate,仅保留月和日信息LocalDate timeDate = time.toLocalDate();LocalDate startDate;LocalDate endDate;try {// 解析起始日期字符串,并与当前年份结合TemporalAccessor startTemporal = formatter.parse(startTime);startDate = LocalDate.of(time.getYear(), startTemporal.get(ChronoField.MONTH_OF_YEAR), startTemporal.get(ChronoField.DAY_OF_MONTH));// 解析结束日期字符串,并与当前年份结合TemporalAccessor endTemporal = formatter.parse(endTime);endDate = LocalDate.of(time.getYear(), endTemporal.get(ChronoField.MONTH_OF_YEAR), endTemporal.get(ChronoField.DAY_OF_MONTH));// 如果结束日期早于起始日期(跨年情况),将结束日期加一年if (endDate.isBefore(startDate)) {endDate = endDate.plusYears(1);}} catch (Exception e) {// 解析过程中如果发生异常,返回falseSystem.err.println("解析日期时发生错误: " + e.getMessage());return false;}// 判断时间是否在起始日期和结束日期之间(包括边界)return !timeDate.isBefore(startDate) && !timeDate.isAfter(endDate);}
2. 仅比较:时-分(HH:mm)
/*** 判断时间是否在指定的起始和结束时间之间(包含开始时间,不包含结束时间)。** @param startTime HH:mm格式的时间* @param endTime HH:mm格式的时间* @param time 需要判断的时间* @return 如果时间在范围内返回true,否则返回false*/public static boolean isTimeBetweenOfHHmm(String startTime, String endTime, LocalDateTime time) {// 定义时间格式器DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");try {// 补全时间格式,如果输入的时间长度为4位,例如"9:30",补全为"09:30"startTime = startTime.length() == 4 ? "0" + startTime : startTime;endTime = endTime.length() == 4 ? "0" + endTime : endTime;// 解析起始时间,并与当前日期结合TemporalAccessor startTemporal = formatter.parse(startTime);LocalDateTime startDate = LocalDateTime.of(time.getYear(), time.getMonthValue(), time.getDayOfMonth(),startTemporal.get(ChronoField.HOUR_OF_DAY), startTemporal.get(ChronoField.MINUTE_OF_HOUR));// 解析结束时间,并与当前日期结合TemporalAccessor endTemporal = formatter.parse(endTime);LocalDateTime endDate = LocalDateTime.of(time.getYear(), time.getMonthValue(), time.getDayOfMonth(),endTemporal.get(ChronoField.HOUR_OF_DAY), endTemporal.get(ChronoField.MINUTE_OF_HOUR));// 如果结束时间为"24:00",则将其视为第二天的00:00if (endTime.equals("24:00")) {endDate = endDate.plusDays(1).withHour(0).withMinute(0);}// 比较时间是否在起始时间和结束时间之间(包含开始时间,不包含结束时间)return !time.isBefore(startDate) && time.isBefore(endDate);} catch (Exception e) {// 如果解析时间格式失败,返回falseSystem.err.println("解析时间时发生错误: " + e.getMessage());return false;}}
3. 时间先后:LocalDate **
/*** 判断给定日期是否在某个日期的范围内(只比较日期,忽略时间)。** @param startDate 起始日期* @param endDate 结束日期* @param date 需要判断的日期* @return 如果日期在范围内(包括边界)返回true,否则返回false*/public static boolean isDateBetween(LocalDate startDate, LocalDate endDate, LocalDate date) {// 参数检查,确保输入的日期不为空if (startDate == null || endDate == null || date == null) {return false;}// 检查起始日期是否在结束日期之后if (startDate.isAfter(endDate)) {System.err.println("起始日期不能在结束日期之后");return false;}// 判断给定日期是否在范围内(包括边界)return !date.isBefore(startDate) && !date.isAfter(endDate);}
4. 判断日期是否为周末
/*** 判断给定的时间是否为周末。** @param time 需要判断的时间* @return 如果是周末返回true,否则返回false*/public static boolean isWeekend(LocalDateTime time) {// 参数检查,确保输入的时间不为空if (time == null) {throw new IllegalArgumentException("时间不能为空");}// 获取给定时间对应的星期几DayOfWeek dayOfWeek = time.getDayOfWeek();// 如果是周六或周日,返回truereturn dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY;}
5. 转换-字符串为: LocalDateTime,支持多种常见格式 **
/*** 将字符串转换为LocalDateTime,支持多种常见格式。** @param dateTimeStr 日期时间字符串* @return 转换后的LocalDateTime对象,解析失败时返回null*/public static LocalDateTime parseDateTime(String dateTimeStr) {// 定义支持的日期时间格式DateTimeFormatter[] formatters = {DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"),DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm"),DateTimeFormatter.ofPattern("yyyyMMddHHmmss"),DateTimeFormatter.ISO_DATE_TIME};// 遍历所有格式,尝试解析字符串for (DateTimeFormatter formatter : formatters) {try {return LocalDateTime.parse(dateTimeStr, formatter);} catch (DateTimeParseException e) {// 捕获解析异常,继续尝试下一个格式// 可以选择打印调试信息或记录日志}}// 如果无法解析,打印错误并返回nullSystem.err.println("无法解析日期时间字符串: " + dateTimeStr);return null;}
6. 计算两个时间-分钟差
/*** 获取两个时间之间的分钟差。** @param startTime 起始时间* @param endTime 结束时间* @return 分钟差,如果起始时间晚于结束时间返回负值*/public static long getMinutesBetween(LocalDateTime startTime, LocalDateTime endTime) {// 检查输入的时间是否为空if (startTime == null || endTime == null) {throw new IllegalArgumentException("起始时间和结束时间不能为空");}// 计算两个时间之间的分钟差return ChronoUnit.MINUTES.between(startTime, endTime);}
7. LocalDateTime-转换为指定格式-字符串 **
/*** 将LocalDateTime转换为指定格式的字符串。** @param time 需要转换的时间* @param format 目标格式* @return 格式化后的字符串*/public static String formatDateTime(LocalDateTime time, String format) {// 参数检查,确保时间和格式不为空if (time == null || format == null || format.isEmpty()) {throw new IllegalArgumentException("时间和格式不能为空");}try {// 创建日期时间格式化器DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);// 将时间格式化为指定格式的字符串return time.format(formatter);} catch (IllegalArgumentException e) {// 捕获并处理格式无效的异常throw new IllegalArgumentException("无效的日期格式: " + format, e);}}
8. 判断:是否为闰年
/*** 判断给定时间所在的年份是否为闰年。** @param time 需要判断的时间* @return 如果为闰年返回true,否则返回false*/public static boolean isLeapYear(LocalDateTime time) {// 检查输入的时间是否为空if (time == null) {throw new IllegalArgumentException("时间不能为空");}// 将LocalDateTime转换为LocalDate,并判断是否为闰年return time.toLocalDate().isLeapYear();}
9. 转换:秒数为HH:mm:ss字符串
/*** 将秒数转换为HH:mm:ss格式的字符串。** @param seconds 秒数* @return HH:mm:ss格式的字符串*/public static String secondsToHHmmss(long seconds) {// 检查输入的秒数是否为负数if (seconds < 0) {throw new IllegalArgumentException("秒数不能为负数");}// 计算小时、分钟和秒long hours = seconds / 3600;long minutes = (seconds % 3600) / 60;long secs = seconds % 60;// 格式化为HH:mm:ss格式的字符串return String.format("%02d:%02d:%02d", hours, minutes, secs);}
10. 计算两个时间-天数差 **
/*** 获取两个日期之间的天数差。** @param startDate 起始日期* @param endDate 结束日期* @return 天数差,如果起始日期晚于结束日期返回负值*/public static long getDaysBetween(LocalDate startDate, LocalDate endDate) {// 检查输入的日期是否为空if (startDate == null || endDate == null) {throw new IllegalArgumentException("起始日期和结束日期不能为空");}// 计算两个日期之间的天数差return ChronoUnit.DAYS.between(startDate, endDate);}
11. 计算:日期下一个指定工作日(周一至周五)
/*** 计算给定日期的下一个指定工作日(周一至周五)。** @param date 给定日期* @return 下一个工作日*/public static LocalDate getNextBusinessDay(LocalDate date) {// 检查输入日期是否为空if (date == null) {throw new IllegalArgumentException("日期不能为空");}// 初步将日期加一天LocalDate nextDate = date.plusDays(1);DayOfWeek dayOfWeek = nextDate.getDayOfWeek();// 使用switch语句处理周末的情况switch (dayOfWeek) {case SATURDAY:// 如果是周六,则加两天跳到下周一nextDate = nextDate.plusDays(2);break;case SUNDAY:// 如果是周日,则加一天跳到下周一nextDate = nextDate.plusDays(1);break;default:// 如果是工作日,直接返回nextDatebreak;}return nextDate;}
12. 获取:某天的开始时间(即 00:00:00)**
/*** 获取某天的开始时间(即00:00:00)。** @param date 给定日期* @return 该日期的开始时间*/public static LocalDateTime getStartOfDay(LocalDate date) {// 检查输入的日期是否为空if (date == null) {throw new IllegalArgumentException("日期不能为空");}// 使用LocalDate的atStartOfDay方法获取当天的00:00:00return date.atStartOfDay();}
13. 获取:某天的结束时间(即 23:59:59)**
/*** 获取某天的结束时间(即23:59:59)。** @param date 给定日期* @return 该日期的结束时间*/public static LocalDateTime getEndOfDay(LocalDate date) {// 检查输入的日期是否为空if (date == null) {throw new IllegalArgumentException("日期不能为空");}// 设置时间为23:59:59,不包含纳秒return date.atTime(LocalTime.of(23, 59, 59));}
14. 计算:两个日期之间的工作日天数(不包括周末)
/*** 计算两个日期之间的工作日天数(不包括周末)。** @param startDate 起始日期* @param endDate 结束日期* @return 工作日天数*/public static long getBusinessDaysBetween(LocalDate startDate, LocalDate endDate) {// 检查输入的日期是否为空if (startDate == null || endDate == null) {throw new IllegalArgumentException("起始日期和结束日期不能为空");}// 确保startDate不晚于endDate,否则交换两者if (startDate.isAfter(endDate)) {LocalDate temp = startDate;startDate = endDate;endDate = temp;}// 计算两日期之间的天数long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);// 遍历并计算工作日long businessDays = 0;for (int i = 0; i <= daysBetween; i++) {DayOfWeek dayOfWeek = startDate.plusDays(i).getDayOfWeek();if (dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY) {businessDays++;}}return businessDays;}
15. 计算:当前时间-指定日期的 天数 **
/*** 计算从当前时间到指定日期的天数。** @param targetDate 目标日期* @return 从当前时间到目标日期的天数。如果目标日期在当前日期之前,返回负值*/public static long daysUntil(LocalDate targetDate) {if (targetDate == null) {throw new IllegalArgumentException("目标日期不能为空");}// 获取当前日期LocalDate today = LocalDate.now();// 计算从当前日期到目标日期的天数return ChronoUnit.DAYS.between(today, targetDate);}
16. 计算:两个时间-之间的 小时数
/*** 计算两个时间点之间的小时数。** @param startTime 起始时间* @param endTime 结束时间* @return 两个时间点之间的小时数。如果起始时间晚于结束时间,返回负值*/public static long hoursBetween(LocalDateTime startTime, LocalDateTime endTime) {if (startTime == null || endTime == null) {throw new IllegalArgumentException("起始时间和结束时间不能为空");}// 计算两个时间点之间的小时数return ChronoUnit.HOURS.between(startTime, endTime);}
17. 判断:日期是否是-月末
/*** 判断给定日期是否是本月的最后一天。** @param date 给定日期* @return 如果是本月的最后一天返回true,否则返回false*/public static boolean isLastDayOfMonth(LocalDate date) {// 检查输入的日期是否为空if (date == null) {throw new IllegalArgumentException("日期不能为空");}// 获取本月的最后一天LocalDate lastDayOfMonth = date.withDayOfMonth(date.lengthOfMonth());// 比较给定日期和本月的最后一天是否相同return date.equals(lastDayOfMonth);}
18. 获取:当前季度的开始和结束日期
/*** 获取当前季度的开始和结束日期。** @return 当前季度的开始和结束日期,返回一个包含两个 LocalDate 对象的数组*/public static LocalDate[] getCurrentQuarterDates() {LocalDate now = LocalDate.now();int month = now.getMonthValue();LocalDate startDate;LocalDate endDate;// 确定当前季度的开始和结束日期if (month <= 3) {startDate = LocalDate.of(now.getYear(), 1, 1);endDate = LocalDate.of(now.getYear(), 3, 31);} else if (month <= 6) {startDate = LocalDate.of(now.getYear(), 4, 1);endDate = LocalDate.of(now.getYear(), 6, 30);} else if (month <= 9) {startDate = LocalDate.of(now.getYear(), 7, 1);endDate = LocalDate.of(now.getYear(), 9, 30);} else {startDate = LocalDate.of(now.getYear(), 10, 1);endDate = LocalDate.of(now.getYear(), 12, 31);}return new LocalDate[]{startDate, endDate};}
19. 计算:日期的下一个工作日的日期(跳过节假日、周末)
/*** 计算给定日期的下一个工作日的日期(跳过节假日)。** @param date 给定日期* @param holidays 节假日列表* @return 下一个工作日的日期*/public static LocalDate getNextBusinessDayWithHolidays(LocalDate date, LocalDate[] holidays) {if (date == null || holidays == null) {throw new IllegalArgumentException("日期和节假日列表不能为空");}// 将节假日列表转换为Set以提高查询效率Set<LocalDate> holidaySet = new HashSet<>();for (LocalDate holiday : holidays) {holidaySet.add(holiday);}LocalDate nextDate = date.plusDays(1);// 查找下一个工作日,跳过周末和节假日while (nextDate.getDayOfWeek() == DayOfWeek.SATURDAY|| nextDate.getDayOfWeek() == DayOfWeek.SUNDAY|| holidaySet.contains(nextDate)) {nextDate = nextDate.plusDays(1);}return nextDate;}
20. LocalDateTime 转换为 LocalDate,只保留年月日部分 **
/*** 将 LocalDateTime 转换为 LocalDate,只保留年月日部分。** @param dateTime 需要转换的 LocalDateTime 对象* @return 只包含年月日的 LocalDate 对象* @throws IllegalArgumentException 如果 dateTime 为 null*/public static LocalDate toLocalDate(LocalDateTime dateTime) {if (dateTime == null) {throw new IllegalArgumentException("LocalDateTime 不能为空");}return dateTime.toLocalDate();}
21. LocalDate 转换为 LocalDateTime,设置时间部分为 00:00:00 **
/*** 将 LocalDate 转换为 LocalDateTime,设置时间部分为 00:00:00。** @param date 需要转换的 LocalDate 对象* @return LocalDateTime 对象,时间部分为 00:00:00* @throws IllegalArgumentException 如果 date 为 null*/public static LocalDateTime toStartOfDay(LocalDate date) {if (date == null) {throw new IllegalArgumentException("LocalDate 不能为空");}return date.atStartOfDay();}
这篇关于【时间】常见-时间处理函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!