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

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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<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;
}
}