package com.ruzhoukj.sms.util; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.temporal.ChronoUnit; import java.util.Date; /** * @author 邬吉朋 */ public class DateUtils { /** * 获取当前月份的开始和结束日期。 * * @return 一个包含两个元素的数组,第一个元素是当前月份的开始日期, * 第二个元素是当前月份的结束日期。 */ public static Date[] getStartAndEndDateOfCurrentMonth() { // 获取当前日期 LocalDate today = LocalDate.now(); // 获取本月第一天和最后一天 LocalDate firstDate = today.withDayOfMonth(1); LocalDate lastDate = today.withDayOfMonth(today.lengthOfMonth()); // 转换为LocalDateTime并设置时间 LocalDateTime firstDateTime = firstDate.atStartOfDay(); // 本月第一天的开始时间 LocalDateTime lastDateTime = lastDate.atTime(23, 59, 59); // 本月最后一天的结束时间 // 转换为Date Date startDate = Date.from(firstDateTime.atZone(ZoneId.systemDefault()).toInstant()); Date endDate = Date.from(lastDateTime.atZone(ZoneId.systemDefault()).toInstant()); return new Date[]{startDate, endDate}; } /** * 将Date类型的日期转换为"yyyy-MM-dd"格式的字符串. * * @param date 需要被转换的日期 * @return 转换后的字符串,如果输入的date为null则返回null */ public static String formatDate(Date date) { if (date == null) { return null; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(date); } /** * 计算两个日期之间的天数差。 * * @param date1 第一个日期 * @param date2 第二个日期 * @return 两个日期之间的天数差 */ public static long daysBetween(Date date1, Date date2) { // 将Date对象转换为LocalDate对象 LocalDate localDate1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate localDate2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); // 计算两个日期之间的天数差 return ChronoUnit.DAYS.between(localDate1, localDate2); } /** * 将 LocalDate 转换为 Date * * @param localDate 要转换的 LocalDate 对象 * @return 转换后的 Date 对象 */ public static Date convertLocalDateToDate(LocalDate localDate) { if (localDate == null) { return null; // 处理 null 值 } return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); } }