import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
public enum DateUtil {
instance;
private static final SimpleDateFormat DD_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat SSS_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
private static final SimpleDateFormat MM_FORMAT = new SimpleDateFormat("yyyy-MM");
private static final String START_SUFFIX = " 00:00:00.000";
private static final String END_SUFFIX = " 23:59:59.999";
public Date endOfDay(Date date) throws ParseException {
Date end = SSS_FORMAT.parse(DD_FORMAT.format(date) + END_SUFFIX);
return end;
}
public Date endOfDay(String date) throws ParseException {
Date end = SSS_FORMAT.parse(date + END_SUFFIX);
return end;
}
public Date startOfDay(Date date) throws ParseException {
Date start = SSS_FORMAT.parse(DD_FORMAT.format(date) + START_SUFFIX);
return start;
}
public Date startOfDay(String date) throws ParseException {
Date start = SSS_FORMAT.parse(date + START_SUFFIX);
return start;
}
public Date endOfMM(String endTime) throws ParseException {
Date date = MM_FORMAT.parse(endTime);
LocalDate localDate = date2LocalDate(date);
Date endOfMonth = localDate2Date(localDate.withDayOfMonth(localDate.lengthOfMonth()));
return endOfDay(endOfMonth);
}
public Date startOfMM(Date startTime) throws ParseException {
LocalDate localDate = date2LocalDate(startTime);
Date startOfMonth = localDate2Date(localDate.withDayOfMonth(1));
return startOfDay(startOfMonth);
}
public Date endOfMM(Date endTime) throws ParseException {
LocalDate localDate = date2LocalDate(endTime);
Date endOfMonth = localDate2Date(localDate.withDayOfMonth(localDate.lengthOfMonth()));
return endOfDay(endOfMonth);
}
public Date startOfMM(String startTime) throws ParseException {
Date date = MM_FORMAT.parse(startTime);
LocalDate localDate = date2LocalDate(date);
Date startOfMonth = localDate2Date(localDate.withDayOfMonth(1));
return startOfDay(startOfMonth);
}
public Date localDate2Date(LocalDate localDate) {
if (null == localDate) {
return null;
}
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
return Date.from(zonedDateTime.toInstant());
}
public LocalDate date2LocalDate(Date date) {
if (null == date) {
return null;
}
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
public Date getEarliestDate() throws ParseException {
return startOfMM("1997-01");
}
/**
* 在给定的日期加上或减去指定月份后的日期
*
* @param sourceDate 原始时间
* @param month 要调整的月份,向前为负数,向后为正数
* @return
*/
public static Date stepMonth(Date sourceDate, int month) {
Calendar c = Calendar.getInstance();
c.setTime(sourceDate);
c.add(Calendar.MONTH, month);
return c.getTime();
}
public static void main(String[] args) throws ParseException {
System.out.println(instance.startOfDay("2020-01-01"));
}
}
处理日期工具类(枚举单例实现)
最新推荐文章于 2024-09-08 11:09:43 发布