You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
weaver-develop/src/com/engine/matfron/util/CommonDateUtil.java

95 lines
2.6 KiB
Java

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";
/**
* YearMonthDate
* dayOfMonth13122928
* 使toDateEndOfMonth(YearMonth)
*
* @param yearMonth
* @param dayOfMonth
* @return
*/
public static Date toDate(YearMonth yearMonth, int dayOfMonth) {
Objects.requireNonNull(yearMonth, "yearMonth");
return localDateToDate(yearMonth.atDay(dayOfMonth));
}
/**
* YearMonthDate
*
* @param yearMonth
* @return
*/
public static Date toDateStartOfMonth(YearMonth yearMonth) {
return toDate(yearMonth, 1);
}
/**
* YearMonthDate
*
* @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<YearMonth> getYearMonths(LocalDate date) {
List<YearMonth> yearMonths = new ArrayList<>();
for (int month = 1; month <= 12; month++) {
LocalDate firstDayOfMonth = date.withMonth(month);
yearMonths.add(YearMonth.from(firstDayOfMonth));
}
return yearMonths;
}
}