package com.engine.matfron.util; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.YearMonth; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; /** * @Author liang.cheng * @Date 2023/9/27 4:44 PM * @Description: * @Version 1.0 */ @Slf4j public class CommonDateUtil { public static final String DATE_FORMATTER_PATTERN = "yyyy-MM-dd"; /** * YearMonth转Date * 注意dayOfMonth范围:1到31之间,最大值根据月份确定特殊情况,如2月闰年29,非闰年28 * 如果要转换为当月最后一天,可以使用下面方法:toDateEndOfMonth(YearMonth) * * @param yearMonth * @param dayOfMonth * @return */ public static Date toDate(YearMonth yearMonth, int dayOfMonth) { Objects.requireNonNull(yearMonth, "yearMonth"); return localDateToDate(yearMonth.atDay(dayOfMonth)); } /** * YearMonth转Date,转换为当月第一天 * * @param yearMonth * @return */ public static Date toDateStartOfMonth(YearMonth yearMonth) { return toDate(yearMonth, 1); } /** * YearMonth转Date,转换为当月最后一天 * * @param yearMonth * @return */ public static Date toDateEndOfMonth(YearMonth yearMonth) { Objects.requireNonNull(yearMonth, "yearMonth"); return localDateToDate(yearMonth.atEndOfMonth()); } public static Date localDateToDate(LocalDate localDate) { if (null == localDate) { return null; } ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault()); return Date.from(zonedDateTime.toInstant()); } public static String getFormatYear(Date localDate) { if (localDate == null) { return StringUtils.EMPTY; } try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMATTER_PATTERN); return simpleDateFormat.format(localDate); } catch (Exception e) { log.warn("格式化年份错误", e); return StringUtils.EMPTY; } } public static List getYearMonths(LocalDate date) { List yearMonths = new ArrayList<>(); for (int month = 1; month <= 12; month++) { LocalDate firstDayOfMonth = date.withMonth(month); yearMonths.add(YearMonth.from(firstDayOfMonth)); } return yearMonths; } }