import com.demo.xzm.newTool.emnu.EnumDateType;
import com.demo.xzm.newTool.emnu.EnumDateType2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Arrays;
import java.util.Date;
public class NewDateUtil {
private static final Logger logger = LoggerFactory.getLogger(NewDateUtil.class);
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final String ERROR_MSG = "输入内容有误!当前仅支持 yyyy-MM-dd、yyyy/MM/dd 格式的字符串、Date 类型的日期、LocalDate 以及 InStant 类型的日期)";
/**
* 对时间进行任意的加减。eg. 获取 2021-6-9 10:34:05 近24小时
*
* @param t
* @param plusNum
* @param <T>
*/
public static <T> String datePlusOrMinus(T t, EnumDateType2 enumDateType2, long plusNum) {
LocalDateTime localDateTime = converOtherType2LDT(t);
if (enumDateType2 == EnumDateType2.HOUR) {// 按 小时
localDateTime = localDateTime.plusHours(plusNum);
} else if (enumDateType2 == EnumDateType2.DAY) {// 按 天
localDateTime = localDateTime.plusDays(plusNum);
} else if (enumDateType2 == EnumDateType2.MONTH) {// 按 月
localDateTime = localDateTime.plusMonths(plusNum);
} else if (enumDateType2 == EnumDateType2.YEAR) {// 按 年
localDateTime = localDateTime.plusYears(plusNum);
}
return localDateTime.format(DATE_TIME_FORMATTER);
}
/**
* 获取指定的时间差:eg. [近 7 小时, 现在]
*
* @param t
* @param <T>
* @return
*/
public static <T> String[] getDate(T t, EnumDateType enumDateType) {
return method(t, enumDateType, null);
}
public static <T> String[] getDate(T t, EnumDateType enumDateType, int num) {
return method(t, enumDateType, num);
}
/**
* 判断日期是否在范围内
*
* @param sourceDate 被比较日期
* @param startDate 开始日期
* @param endDate 结束日期
* @return
*/
public static <T> boolean checkDateRange(T sourceDate, T startDate, T endDate) {
LocalDate sourceDateNew = converOtherType2LD(sourceDate);
LocalDate startDateNew = converOtherType2LD(startDate).minusDays(1);
LocalDate endDateNew = converOtherType2LD(endDate).plusDays(1);
return sourceDateNew.isBefore(endDateNew) && sourceDateNew.isAfter(startDateNew);
}
/**
* 获取日期的开始和结束时间
*
* @param t
* @param <T>
* @return
*/
public static <T> String[] getDayStartAndEndTime(T t) {
String[] result = new String[2];
LocalDate date = converOtherType2LD(t);
result[0] = LocalDateTime.of(date, LocalTime.MIN).format(DATE_TIME_FORMATTER);
result[1] = LocalDateTime.of(date, LocalTime.MAX).format(DATE_TIME_FORMATTER);
Arrays.stream(result).forEach(System.out::println);
return result;
}
/**
* 获取指定日期的周一(Monday)和周日(Sunday)
*
* @param t
* @param <T>
* @return
*/
public static <T> String[] getWeekStartAndEndDate(T t) {
String[] result = new String[2];
//LocalDate date = converOtherType2LD(t);
//LocalDate todayOfLastWeek = date.minusDays(7);
//result[0] = convertLocalDate2LDString(todayOfLastWeek.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).plusDays(1));
//result[1] = convertLocalDate2LDString(todayOfLastWeek.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).minusDays(1));
//return result;
LocalDate date = converOtherType2LD(t);
// 所在周开始时间
result[0] = convertLocalDate2LDString(date.with(DayOfWeek.MONDAY));
// 所在周结束时间
result[1] = convertLocalDate2LDString(date.with(DayOfWeek.SUNDAY));
return result;
}
/**
* 获取日期的月初和月末
*
* @param t
* @param <T>
* @return
*/
public static <T> String[] getMonthStartAndEndDate(T t) {
String[] result = new String[2];
LocalDate date = converOtherType2LD(t);
result[0] = convertLocalDate2LDString(date.with(TemporalAdjusters.firstDayOfMonth()));
result[1] = convertLocalDate2LDString(date.with(TemporalAdjusters.lastDayOfMonth()));
Arrays.stream(result).forEach(System.out::println);
return result;
}
/**
* 功能:获取每月的天数
*
* @param t 日期(Date)/LocalDate/String 均可
* @param <T>
* @return
*/
public static <T> int getMonthCount(T t) {
// 获取每月的天数
return converOtherType2LD(t).lengthOfMonth();
}
/**
* 功能:获取当前日期的周一和周日
*/
public static <T> String[] getMondayAndSunday(T t) {
LocalDate date = null;
if (t instanceof String) {
date = LocalDate.parse(parseUnStandardString2LDString((String) t), DATE_FORMATTER);
} else if (t instanceof LocalDate) {
date = (LocalDate) t;
} else if (t instanceof LocalDateTime) {
date = convertLocalDateTime2LD((LocalDateTime) t);
} else if (t instanceof Date) {
date = ((Date) t).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//date = ((Date) t).toInstant().atZone(ZoneOffset.ofHours(0)).toLocalDate();
} else if (t instanceof Instant) {
date = convertInstant2LD((Instant) t);
} else {
throw new RuntimeException(ERROR_MSG);
}
String[] startAndEndDate = new String[2];
if (!date.getDayOfWeek().equals(DayOfWeek.MONDAY)) {
startAndEndDate[0] = date.with(TemporalAdjusters.previous(DayOfWeek.MONDAY)).toString();
} else {
startAndEndDate[0] = date.toString();
}
if (!date.getDayOfWeek().equals(DayOfWeek.SUNDAY)) {
startAndEndDate[1] = date.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)).toString();
} else {
startAndEndDate[1] = date.toString();
}
Arrays.stream(startAndEndDate).forEach(System.out::println);
return startAndEndDate;
}
/**
* 功能:解析日期字符串 & 日期格式化 功能二合一
*
* @param t
* @param <T>
* @param <R>
* @return
*/
public static <T, R> R dateFormatOrParse(T t, Class<R> clazz) {
if (!(t instanceof String || t instanceof LocalDate || t instanceof LocalDateTime || t instanceof Date || t instanceof Instant)) {
throw new RuntimeException(ERROR_MSG);
}
if ("java.lang.String".equalsIgnoreCase(clazz.getName())) {
return (R) converOtherType2MatchString(t);
} else if ("java.time.LocalDate".equalsIgnoreCase(clazz.getName())) {
return (R) converOtherType2LD(t);
} else if ("java.time.LocalDateTime".equalsIgnoreCase(clazz.getName())) {
return (R) converOtherType2LDT(t);
} else if ("java.util.Date".equalsIgnoreCase(clazz.getName())) {
return (R) converOtherType2Date(t);
} else if ("java.time.Instant".equalsIgnoreCase(clazz.getName())) {
return (R) converOtherType2Instant(t);
}
throw new RuntimeException(ERROR_MSG);
}
//////////////////////////////////////////////////////////////// ↓
/**
* 将 String、Date 类型转成 LocalDate 类型
*
* @param t
* @param <T>
* @return
*/
public static <T> LocalDate converOtherType2LD(T t) {
if (t instanceof String) {
return converString2LD((String) t);
} else if (t instanceof Date) {
return convertDate2LD((Date) t);
} else if (t instanceof LocalDate) {
return (LocalDate) t;
} else if (t instanceof LocalDateTime) {
return converOtherType2LD(convertLocalDateTime2LD((LocalDateTime) t));
} else if (t instanceof Instant) {
return convertInstant2LD((Instant) t);
}
throw new RuntimeException("当前日期格式/类型不支持转换");
}
/**
* 功能:将 String、Date、LocalDateTime、Instant 类型日期转成 LocalDateTime
*
* @param t 时间字符串 or Date or LocalDateTime 类型
* @return
*/
public static <T> LocalDateTime converOtherType2LDT(T t) {
if (t instanceof String) {
return converString2LDT((String) t);
} else if (t instanceof LocalDate) {
return convertLocalDate2LDT((LocalDate) t);
} else if (t instanceof LocalDateTime) {
return (LocalDateTime) t;
} else if (t instanceof Date) {
return convertDate2LDT((Date) t);
} else if (t instanceof Instant) {
return convertInstant2LDT((Instant) t);
}
throw new RuntimeException("当前日期格式不支持");
}
public static <T> Date converOtherType2Date(T t) {
if (t instanceof String) {
return converString2Date((String) t);
} else if (t instanceof Date) {
return (Date) t;
} else if (t instanceof LocalDate) {
return converOtherType2Date(convertLocalDate2LDT((LocalDate) t));
} else if (t instanceof LocalDateTime) {// 主
return convertLocalDateTime2Date((LocalDateTime) t);
} else if (t instanceof Instant) {
return converOtherType2Date(convertInstant2LDT((Instant) t));
}
throw new RuntimeException("当前日期格式/类型不支持转换");
}
public static <T> Instant converOtherType2Instant(T t) {
if (t instanceof String) {
return converOtherType2Instant(converString2LDT((String) t));
} else if (t instanceof Date) {
return converOtherType2Instant(convertDate2LDT((Date) t));
} else if (t instanceof LocalDate) {
return converOtherType2Instant(convertLocalDate2LDT((LocalDate) t));
} else if (t instanceof LocalDateTime) {// (主)
return convertLocalDateTime2Instant((LocalDateTime) t);
} else if (t instanceof Instant) {
return (Instant) t;
}
throw new RuntimeException("当前日期格式/类型不支持转换");
}
/**
* 将日期/时间转成对应的字符串
*
* @param t
* @param <T>
* @return
*/
public static <T> String converOtherType2MatchString(T t) {
if (t instanceof String) {
return parseUnStandardString2MatchString((String) t);
} else if (t instanceof Date) {
return converOtherType2MatchString(convertDate2LDT((Date) t));
} else if (t instanceof LocalDate) {
return convertLocalDate2LDString((LocalDate) t);
} else if (t instanceof LocalDateTime) {// 主
return convertLocalDateTime2LDTString((LocalDateTime) t);
} else if (t instanceof Instant) {
return converOtherType2MatchString(convertInstant2LDT((Instant) t));
}
throw new RuntimeException(ERROR_MSG);
}
//////////////////////////////////////////////////////////////// ↑
private static String convertLocalDateTime2LDTString(LocalDateTime t) {
return t.format(DATE_TIME_FORMATTER);
}
private static Instant convertLocalDateTime2Instant(LocalDateTime t) {
return t.atZone(ZoneOffset.ofHours(0)).toInstant();
}
private static LocalDateTime convertDate2LDT(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
private static LocalDateTime convertInstant2LDT(Instant instant) {
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
private static String convertInstant2LDTString(Instant instant) {
return convertLocalDateTime2LDTString(LocalDateTime.ofInstant(instant, ZoneId.systemDefault()));
}
private static LocalDate convertInstant2LD(Instant instant) {
return convertLocalDateTime2LD(LocalDateTime.ofInstant(instant, ZoneId.systemDefault()));
}
private static LocalDate convertDate2LD(Date date) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//return date.toInstant().atZone(ZoneOffset.ofHours(0)).toLocalDate();
}
private static Date convertLocalDateTime2Date(LocalDateTime time) {
return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
//return Date.from(time.atZone(ZoneOffset.ofHours(0)).toInstant());
}
private static Date convertLocalDate2Date(LocalDate time) {
return Date.from(time.atStartOfDay(ZoneId.systemDefault()).toInstant());
//return Date.from(time.atStartOfDay(ZoneOffset.ofHours(0)).toInstant());
}
private static String convertLocalDate2LDString(LocalDate localDate) {
return localDate.format(DATE_FORMATTER);
}
private static LocalDate convertLocalDateTime2LD(LocalDateTime t) {
return LocalDate.of(t.getYear(), t.getMonthValue(), t.getDayOfMonth());
}
private static LocalDateTime convertLocalDate2LDT(LocalDate t) {
return LocalDateTime.of(t, LocalTime.of(0, 0, 0));
}
/**
* 将字符串转成 LocalDateTime
*
* @param t
* @return
*/
private static LocalDateTime converString2LDT(String t) {
return LocalDateTime.parse(parseUnStandardString2LDTString(t), DATE_TIME_FORMATTER);
}
/**
* 将字符串转成 LocalDate
*
* @param t
* @return
*/
private static LocalDate converString2LD(String t) {
return parseUnStandardString2LD(t);
}
/**
* 将 LocalDateTime 转成 Date
*
* @param t
* @return
*/
private static Date converString2Date(String t) {
return convertLocalDate2Date(converString2LD(t));
}
/**
* 不规范的日期格式转成标准可解析格式字符串,然后转成 LocalDate
*
* @param t
* @param <T>
* @return
*/
private static <T> LocalDate parseUnStandardString2LD(String t) {
LocalDate resultLocalDate;
String temp = t.replaceAll(" ", "");
String[] split = temp.split("-");
if (split.length != 3) {
throw new RuntimeException(ERROR_MSG);
}
if (temp.length() != 10) { // 不规范的日期格式:eg. 2021-6-9、2021-06-9、2021-6-09
resultLocalDate = LocalDate.of(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
} else {
resultLocalDate = LocalDate.parse(temp, DATE_FORMATTER);
}
return resultLocalDate;
}
private static String parseUnStandardString2MatchString(String t) {
return t.contains(":") ? parseUnStandardString2LDTString(t) : parseUnStandardString2LDString(t);
}
private static String parseUnStandardString2LDString(String t) {
// eg. 2021-6-10 14:12:27
String temp = t;
String[] split = null;
String splitChar = null;
if (temp.contains("-")) {
split = temp.split("-");
splitChar = "-";
} else if (temp.contains("/")) {
split = temp.split("/");
splitChar = "/";
}
if (split.length != 3) {
throw new RuntimeException(ERROR_MSG);
}
if (temp.length() != 10) { // 不规范的日期格式:eg. 2021-6-9、2021-06-9、2021-6-09、甚至是 2021-6-10 14:12:27
String s1 = split[0];
String s2 = split[1];
String s3 = split[2];
s1 = String.format("%04d", Integer.parseInt(s1));
s2 = String.format("%02d", Integer.parseInt(s2));
if (s3.contains(" ") && s3.contains(":")) {
s3 = s3.split(" ")[0];
}
s3 = String.format("%02d", Integer.parseInt(s3));
//return s1 + "-" + s2 + "-" + s3;
//return s1 + splitChar + s2 + splitChar + s3;
return new StringBuilder().append(s1).append(splitChar).append(s2).append(splitChar).append(s3).toString();
} else {
return t;
}
}
private static String parseUnStandardString2LDTString(String t) {
String temp = t;
String[] split = temp.split("-");
if (split.length != 3) {
throw new RuntimeException(ERROR_MSG);
}
if (temp.length() <= 10) { // 不规范的日期格式:eg. 2021-6-9、2021-06-9、2021-6-09
String s1 = split[0];
String s2 = split[1];
String s3 = split[2];
s1 = String.format("%04d", Integer.parseInt(s1));
s2 = String.format("%02d", Integer.parseInt(s2));
s3 = String.format("%02d", Integer.parseInt(s3));
return s1 + "-" + s2 + "-" + s3 + " 00:00:00";
} else if (temp.length() != 20) { // 不规范的日期格式:eg. 2021-6-9、2021-06-9、2021-6-09
String s1 = split[0];
String s2 = split[1];
String s3 = split[2].split(" ")[0];
String s4 = split[2].split(" ")[1];
s1 = String.format("%04d", Integer.parseInt(s1));
s2 = String.format("%02d", Integer.parseInt(s2));
s3 = String.format("%02d", Integer.parseInt(s3));
return s1 + "-" + s2 + "-" + s3 + " " + s4;
} else {
return t;
}
}
private static <T> String[] method(T t, EnumDateType enumDateType, Integer num) {
LocalDate date = converOtherType2LD(t);
String[] startAndEndTime = new String[2];// 0、1:时间,2、3:日期
if (enumDateType == EnumDateType.HOUR) {// 近 N 小时(默认24小时)
startAndEndTime[0] = LocalDateTime.of(date, LocalTime.now()).minusHours(num != null ? num : 24).format(DATE_TIME_FORMATTER);
startAndEndTime[1] = LocalDateTime.of(date, LocalTime.now()).format(DATE_TIME_FORMATTER);
} else if (enumDateType == EnumDateType.DAY) {// 近 N 天(默认7天)
startAndEndTime[0] = LocalDateTime.of(date.minusDays(num != null ? num : 7), LocalTime.now()).format(DATE_TIME_FORMATTER);
startAndEndTime[1] = LocalDateTime.of(date.minusDays(0), LocalTime.now()).format(DATE_TIME_FORMATTER);
} else if (enumDateType == EnumDateType.MONTH) {// 近 N 月(默认6个月)
startAndEndTime[0] = LocalDateTime.of(date.minusMonths(num != null ? num : 6), LocalTime.now()).format(DATE_TIME_FORMATTER);
startAndEndTime[1] = LocalDateTime.of(date.minusMonths(0), LocalTime.now()).format(DATE_TIME_FORMATTER);
} else if (enumDateType == EnumDateType.TODAY_TIME) {// 今天的开始和结束时间
startAndEndTime[0] = LocalDateTime.of(date, LocalTime.MIN).format(DATE_TIME_FORMATTER);// 今天 00:00:00
startAndEndTime[1] = LocalDateTime.of(date, LocalTime.MAX).format(DATE_TIME_FORMATTER);// 今天 23:59:59
} else if (enumDateType == EnumDateType.LAST_24_HOUR) {// 近 24 小时(含当天)
startAndEndTime[0] = LocalDateTime.of(date.plusDays(-1), LocalTime.now()).format(DATE_TIME_FORMATTER);
startAndEndTime[1] = LocalDateTime.of(date, LocalTime.now()).format(DATE_TIME_FORMATTER);
} else if (enumDateType == EnumDateType.LAST_30_DAY_CONTAIN_THIS) {// 近 30 天(含当天)
startAndEndTime[0] = LocalDateTime.of(date.plusDays(-30), LocalTime.now()).format(DATE_TIME_FORMATTER);
startAndEndTime[1] = LocalDateTime.of(date.plusDays(-0), LocalTime.now()).format(DATE_TIME_FORMATTER);
} else if (enumDateType == EnumDateType.LAST_30_DAY_NOT_CONTAIN_THIS) {// 近 30 天(不含当天)
startAndEndTime[0] = LocalDateTime.of(date.plusDays(-31), LocalTime.now()).format(DATE_TIME_FORMATTER);
startAndEndTime[1] = LocalDateTime.of(date.plusDays(-1), LocalTime.now()).format(DATE_TIME_FORMATTER);
} else if (enumDateType == EnumDateType.LAST_6_MONTH_CONTAIN_THIS) {// 近 6 个月(含当月)
startAndEndTime[0] = date.plusMonths(-6).format(DATE_FORMATTER);
startAndEndTime[1] = date.plusMonths(-0).format(DATE_FORMATTER);
} else if (enumDateType == EnumDateType.LAST_6_MONTH_NOT_CONTAIN_THIS) {// 近 6 个月(不含当月)
startAndEndTime[0] = date.plusMonths(-7).format(DATE_FORMATTER);
startAndEndTime[1] = date.plusMonths(-1).format(DATE_FORMATTER);
} else if (enumDateType == EnumDateType.LAST_12_MONTH_CONTAIN_THIS) {// 近 12 个月(含)
startAndEndTime[0] = date.plusYears(-1).format(DATE_FORMATTER);
startAndEndTime[1] = date.plusYears(-0).format(DATE_FORMATTER);
}
Arrays.stream(startAndEndTime).forEach(System.out::println);
return startAndEndTime;
}
}
public enum EnumDateType {// 枚举类
HOUR(-1, "按小时"),
DAY(-2, "按天"),
MONTH(-3, "按月"),
TODAY_TIME(0, "今天的开始和结束时间"),
LAST_24_HOUR(1, "最近24小时(含当天)"),
LAST_30_DAY_CONTAIN_THIS(2, "近 30 天(含)"),
LAST_30_DAY_NOT_CONTAIN_THIS(3, "近 30 天(不含)"),
LAST_6_MONTH_CONTAIN_THIS(4, "近 6 月(含)"),
LAST_6_MONTH_NOT_CONTAIN_THIS(5, "近 6 月(不含)"),
LAST_12_MONTH_CONTAIN_THIS(6, "近 6 月(不含)");
private Integer code;
private String desc;
EnumDateType(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
public enum EnumDateType2 {// 枚举类
HOUR(1, "按小时"),
DAY(2, "按天"),
MONTH(3, "按月"),
YEAR(4, "按年");
private Integer code;
private String desc;
EnumDateType2(Integer code) {
this.code = code;
}
EnumDateType2(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}