import cn.hutool.core.text.StrPool;
import com.scggic.hr.service.common.Constant;
import com.scggic.hr.service.common.ServiceException;
import com.scggic.hr.service.ov.common.DateVo;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.time.temporal.ChronoUnit;
import java.util.*;
public class DateUtil {
/**
* 格式化形式:yyyy-MM
*/
public static final String DATE_PATTERN_YYYY_MM = "yyyy-MM";
/**
* 格式化形式:yyyy-MM-dd
*/
public static final String DATE_PATTERN_YYYYMMDD1 = "yyyy-MM-dd";
/**
* 格式化形式:yyyy/MM/dd
*/
public static final String DATE_PATTERN_YYYYMMDD2 = "yyyy/MM/dd";
/**
* 格式化形式:yyyy年MM月dd日
*/
public static final String DATE_PATTERN_YYYYMMDD3 = "yyyy年MM月dd日";
/**
* 格式化形式:yyyy年MM月dd日
*/
public static final String DATE_PATTERN_YYYYMMDD4 = "MM月dd日 HH时mm分";
/**
* 格式化形式:M月d号
*/
public static final String DATE_PATTERN_MD = "M月d号";
/**
* 格式化形式:yyyyMMdd
*/
public static final String DATE_PATTERN_YYYYMMDD = "yyyyMMdd";
/**
* 格式化形式:yyyy-MM-dd HH:MM:SS
*/
public static final String DATE_PATTERN_YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";
/**
* 格式化形式:yyyy-MM-dd HH:MM
*/
public static final String DATE_PATTERN_YYYYMMDDHHMM = "yyyy-MM-dd HH:mm";
/**
* 格式化形式:yyyyMMddHHmmss
*/
public static final String DATE_PATTERN_YYYYMMDDHHMMSS_SSS = "yyyyMMddHHmmssSSS";
/**
* 格式化形式:DATE_PATTERN_YYYYMMDD_HHMMSS_SSS
*/
public static final String DATE_PATTERN_YYYYMMDD_HHMMSS_SSS = "yyyyMMdd-HHmmssSSS";
/**
* 格式化形式:yyyyMMddHHmmss
*/
public static final String DATEPATTERNYYYYMMDDHHMMSS = "yyyyMMddHHmmss";
private static final Calendar calendar = Calendar.getInstance();
/**
* 获取当前的timestamp
*
* @return 2021年2月22日
* @author xiaoMai
*/
public static Timestamp getTimestamp() {
return new Timestamp(System.currentTimeMillis());
}
/**
* 获取当前日期格式的时间
*
* @return 2021年2月23日
* @author xiaoMai
*/
public static Date nowDate(String pattern) {
String nowStringDate = nowStringDate(pattern);
return stringToDate(nowStringDate, pattern);
}
public static String getSysDateStr(String formate) {
SimpleDateFormat sdf = new SimpleDateFormat(formate);
return sdf.format(new Date());
}
/**
* 获取当前字符串类型时间
*
* @param pattern
* @return
*/
public static String nowStringDate(String pattern) {
return dateToString(new Date(), pattern);
}
public static String getCurrentTime(String format) {
if (format == null || "".equals(format)) {
format = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
return sdf.format(Calendar.getInstance().getTime());
}
/**
* 格式化时间为字符串
*
* @param date
* @param pattern yyyy-MM-dd HH:mm
* @return
*/
public static String dateToString(Date date, String pattern) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
} catch (Exception e) {
return "";
}
}
/**
* 格式化字符型为Date型
*
* @param strDate
* @param pattern yyyy-MM-dd
* @return
*/
public static Date stringToDate(String strDate, String pattern) {
try {
long ltime = stringToLong(strDate, pattern);
return new Date(ltime);
} catch (Exception ex) {
return null;
}
}
/**
* 格式化字符型时间为长整型
*
* @param strDate
* @param pattern yyyy-MM-dd
* @return
* @throws ParseException
*/
public static long stringToLong(String strDate, String pattern)
throws ParseException {
Locale locale = Locale.CHINESE;
return stringToLong(strDate, pattern, locale);
}
/**
* 格式化字符型时间为长整型
*
* @param strDate
* @param pattern yyyy-MM-dd
* @param locale
* @return
* @throws ParseException
*/
public static long stringToLong(String strDate, String pattern,
Locale locale) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(pattern, locale);
Date date = sdf.parse(strDate);
return date.getTime();
}
/**
* 获取精确到秒的时间戳
*
* @return
*/
public static int getSecondTimestamp(Date date) {
if (null == date) {
return 0;
}
String timestamp = String.valueOf(date.getTime());
int length = timestamp.length();
if (length > 3) {
return Integer.valueOf(timestamp.substring(0, length - 3));
} else {
return 0;
}
}
public static boolean isADateFormat(int formatIndex, String formatString) {
if (isInternalDateFormat(formatIndex)) {
return true;
}
if ((formatString == null) || (formatString.length() == 0)) {
return false;
}
String fs = formatString;
//下面这一行是自己手动添加的 以支持汉字格式wingzing
fs = fs.replaceAll("[\"|\']", "").replaceAll("[年|月|日|时|分|秒|毫秒|微秒]", "");
fs = fs.replaceAll("\\\\-", "-");
fs = fs.replaceAll("\\\\,", ",");
fs = fs.replaceAll("\\\\.", ".");
fs = fs.replaceAll("\\\\ ", " ");
fs = fs.replaceAll(";@", "");
fs = fs.replaceAll("^\\[\\$\\-.*?\\]", "");
fs = fs.replaceAll("^\\[[a-zA-Z]+\\]", "");
return (fs.matches("^[yYmMdDhHsS\\-/,. :]+[ampAMP/]*$"));
}
public static boolean isInternalDateFormat(int format) {
switch (format) {
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
case 21:
case 22:
case 45:
case 46:
case 47:
return true;
case 23:
case 24:
case 25:
case 26:
case 27:
case 28:
case 29:
case 30:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case 37:
case 38:
case 39:
case 40:
case 41:
case 42:
case 43:
case 44:
}
return false;
}
public static boolean isValidExcelDate(double value) {
return (value > -4.940656458412465E-324D);
}
/**
* 获取当前日期提前或后几天的日期
*
* @param date 日期
* @param day 天数
* @return
*/
public static Date getDayPrior(Date date, Integer day) {
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, day);
return calendar.getTime();
}
/**
* 获取当前日期为星期几,星期天为0
*
* @param date 日期
* @return
*/
public static Integer getDayOfWeek(Date date) {
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK) - 1;
}
/**
* 获取传入日期为本周,上周,下周还是两周前,两周后
*
* @param date 日期
* @return
*/
public static String getCustomDayStr(Date date) {
int daysBetween = 0;
int twoWeekDays = 14;
int oneWeekDays = 7;
Date nowDate = nowDate(DateUtil.DATE_PATTERN_YYYYMMDD1);
try {
daysBetween = daysBetween(nowDate, date);
} catch (Exception e) {
e.printStackTrace();
}
Integer dayOfWeek = getDayOfWeek(date);
Integer nowDateOfWeek = getDayOfWeek(nowDate);
if (daysBetween < 0) {
if (Math.abs(daysBetween) >= (nowDateOfWeek + oneWeekDays)) {
return "两周前";
} else if (Math.abs(daysBetween) >= nowDateOfWeek) {
return "上周" + getDayOfChinese(dayOfWeek);
} else {
return "本周" + getDayOfChinese(dayOfWeek);
}
} else {
if (Math.abs(daysBetween) > (twoWeekDays - nowDateOfWeek)) {
return "两周后";
} else if (Math.abs(daysBetween) > oneWeekDays - nowDateOfWeek) {
return "下周" + getDayOfChinese(dayOfWeek);
} else {
return "本周" + getDayOfChinese(dayOfWeek);
}
}
}
public static String getDayOfChinese(int dayOfWeek) {
String returnStr = null;
switch (dayOfWeek) {
case 0:
returnStr = "日";
break;
case 1:
returnStr = "一";
break;
case 2:
returnStr = "二";
break;
case 3:
returnStr = "三";
break;
case 4:
returnStr = "四";
break;
case 5:
returnStr = "五";
break;
case 6:
returnStr = "六";
break;
}
return returnStr;
}
/**
* 计算两个日期之间相差的天数
*
* @param smdate 较小的时间
* @param bdate 较大的时间
* @return 相差天数
* @throws ParseException
*/
public static int daysBetween(Date smdate, Date bdate) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
smdate = sdf.parse(sdf.format(smdate));
bdate = sdf.parse(sdf.format(bdate));
calendar.setTime(smdate);
long time1 = calendar.getTimeInMillis();
calendar.setTime(bdate);
long time2 = calendar.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
} catch (Exception ex) {
throw new ServiceException("daysBetween:日期转换异常");
}
}
/**
* 根据出生日期获取年龄
*
* @param birthDay
* @return
*/
public static int getAge(Date birthDay) {
Calendar cal = Calendar.getInstance();
//出生日期晚于当前时间,无法计算
if (cal.before(birthDay)) {
throw new ServiceException("出生日期晚于当前时间,无法计算!");
}
//当前年份
int yearNow = cal.get(Calendar.YEAR);
//当前月份
int monthNow = cal.get(Calendar.MONTH);
//当前日期
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDay);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH);
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
//计算整岁数
int age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
//当前日期在生日之前,年龄减一
if (dayOfMonthNow < dayOfMonthBirth) {
age--;
}
} else {
//当前月份在生日之前,年龄减一
age--;
}
}
return age;
}
/**
* @param date
* @return
* @description 转时间
* @author wuyuejun
* @date 2021年12月10日 下午2:01:51
*/
public static Date getDayBytime(Long date) {
calendar.setTimeInMillis(date);
return calendar.getTime();
}
/**
* @return
* @description 当前时间戳
* @author wuyuejun
* @date 2022年1月6日 上午11:42:00
*/
public static Integer getNowDay() {
Long time = System.currentTimeMillis() / 1000;
return Integer.valueOf(time + "");
}
/**
* 根据当前时间获取获取下月开始和结束时间
*
* @return
*/
public static DateVo nextMonthDate() {
DateVo dv = new DateVo();
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1); // 加一个月
calendar.set(Calendar.DAY_OF_MONTH, 1); // 设置为下个月的第一天
Date startDate = calendar.getTime(); // 下个月的开始时间
dv.setBeginDate(startDate);
calendar.add(Calendar.MONTH, 1); // 再加一个月
calendar.add(Calendar.DATE, -1); // 减去一天,即为这个月的最后一天
Date endDate = calendar.getTime(); // 下个月的结束时间
dv.setEndDate(endDate);
return dv;
}
/**
* 根据当前时间获取下个季度开始和结束时间
*
* @return
*/
public static DateVo nextQuarterDate() {
DateVo dv = new DateVo();
Calendar calendar = Calendar.getInstance();
int currentMonth = calendar.get(Calendar.MONTH); // 获取当前月份,从0开始计数
// 计算下个季度的第一个月份
int nextQuarterFirstMonth = (currentMonth / 3 + 1) * 3;
calendar.set(Calendar.MONTH, nextQuarterFirstMonth); // 设置为下个季度的第一个月份
calendar.set(Calendar.DAY_OF_MONTH, 1); // 设置为下个季度的第一天
Date startDate = calendar.getTime(); // 下个季度的开始时间
dv.setBeginDate(startDate);
if (currentMonth >= Constant.INTEGER_6.intValue()) {
calendar.add(Calendar.YEAR, 1); //特殊情况当月分大于等于6月时年份需要加一
}
// 计算下下个季度的第一个月份
int nextNextQuarterFirstMonth = ((currentMonth / 3 + 2) % 4) * 3;
calendar.set(Calendar.MONTH, nextNextQuarterFirstMonth); // 设置为下下个季度的第一个月份
calendar.add(Calendar.DATE, -1); // 减去一天,即为下个季度的最后一天
Date endDate = calendar.getTime(); // 下个季度的结束时间
dv.setEndDate(endDate);
return dv;
}
/**
* 根据当前时间获取下年的起止时间
*
* @return
*/
public static DateVo nextYearDate() {
DateVo dv = new DateVo();
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, 1); // 加一年
calendar.set(Calendar.MONTH, 0); // 设置为下一年的第一个月份(即1月)
calendar.set(Calendar.DAY_OF_MONTH, 1); // 设置为下一年的第一天
Date startDate = calendar.getTime(); // 下一年的开始时间
dv.setBeginDate(startDate);
calendar.add(Calendar.YEAR, 1); // 再加一年
calendar.add(Calendar.DATE, -1); // 减去一天,即为这一年的最后一天
Date endDate = calendar.getTime(); // 下一年的结束时间
dv.setEndDate(endDate);
return dv;
}
/**
* 获取日期年月日
*
* @param data
* @return
*/
public static String getDateStr(Date data) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式
return sdf.format(data); // 将Date对象转换为字符串
}
/**
* 判断一个时间是否在这两个时之间
*
* @param startDate 开始时间
* @param endDate 结束时间
* @param middleDate 获取的时间
* @return 是否存在
*/
public static Boolean middle(Date startDate, Date endDate, Date middleDate) {
Instant startInstant = startDate.toInstant();
Instant endInstant = endDate.toInstant();
Instant middleInstant = middleDate.toInstant();
return middleInstant.isAfter(startInstant) && middleInstant.isBefore(endInstant);
}
/**
* 判断一个时间是否在这两个时之间
*
* @param startDate 开始时间
* @param endDate 结束时间
* @param middleDate 获取的时间
* @return 是否存在
*/
public static Boolean middleYmd(LocalDate startDate, LocalDate endDate, LocalDate middleDate) {
return middleDate.isEqual(startDate) || middleDate.isEqual(endDate) || (middleDate.isAfter(startDate) && middleDate.isBefore(endDate));
}
/**
* 获取两个时间的二分之一的中间时间
*
* @param startDate 开始时间
* @param endDate 结束时间
* @return 二分之一的中间时间
*/
public static Date middleDate(Date startDate, Date endDate) {
Instant startInstant = startDate.toInstant();
Instant endInstant = endDate.toInstant();
Duration middleDate = Duration.between(startInstant, endInstant);
long seconds = middleDate.getSeconds();
long middleSeconds = seconds / 2;
Instant middleInstant = startInstant.plusSeconds(middleSeconds);
long middleTimestamp = middleInstant.getEpochSecond();
Instant middle = Instant.ofEpochSecond(middleTimestamp);
return Date.from(middle);
}
/**
* 获取两个时间之间的所有时间
*
* @param startDate 开始时间
* @param endDate 结束时间
* @return 两个时间之间的所有时间
*/
public static List<LocalDate> dateInterval(LocalDate startDate, LocalDate endDate) {
List<LocalDate> allDates = new ArrayList<>();
LocalDate currentDate = startDate;
while (currentDate.isBefore(endDate.plusDays(1))) {
allDates.add(currentDate);
currentDate = currentDate.plusDays(1);
}
return allDates;
}
/**
* 将Date 转为 LocalDate
*
* @param date 时间格式
* @return
*/
public static LocalDate dateTurnLocalDate(Date date) {
Instant instant = date.toInstant();
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
return zonedDateTime.toLocalDate();
}
/**
* 身份证解析年月日
*
* @param id
* @return
*/
public static Date parseBirthdayFromId(String id) {
if (id == null || id.length() != 18) {
return null;
}
String ymd = id.substring(6, 14);
int year = Integer.parseInt(ymd.substring(0, 4));
int month = Integer.parseInt(ymd.substring(4, 6));
int day = Integer.parseInt(ymd.substring(6, 8));
LocalDate localDate = LocalDate.of(year, month, day);
Instant instant = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
return Date.from(instant);
}
/**
* 根据年份和周数获取指定周的日期
*
* @param years 年
* @param targetWeek 周
* @return 日期
*/
public static List<LocalDate> getDatesByWeek(List<Integer> years, List<DayOfWeek> targetWeek) {
List<LocalDate> dates = new ArrayList<>();
for (Integer year : years) {
for (DayOfWeek dayOfWeek : targetWeek) {
//设置开始日期为当年的1月1日
LocalDate startDate = LocalDate.of(year, 1, 1);
//设置结束日期为当年的12月31日
LocalDate endDate = LocalDate.of(year, 12, 31);
LocalDate currentDate = startDate;
while (currentDate.isBefore(endDate) || currentDate.isEqual(endDate)) {
if (currentDate.getDayOfWeek() == dayOfWeek) {
dates.add(currentDate);
}
// 增加一天
currentDate = currentDate.plusDays(1);
}
}
}
return dates;
}
/**
* 日期转换为LocalDate
*
* @param date 日期
* @return LocalDate
*/
public static LocalDate convertToLocalDate(Date date) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
/**
* 获取指定日期范围内的所有日期(LocalDate)
*
* @param startDate 开始日期
* @param endDate 结束日期
* @return LocalDate日期集合
*/
public static List<LocalDate> getDatesInRange(LocalDate startDate, LocalDate endDate) {
List<LocalDate> dates = new ArrayList<>();
LocalDate currentDate = startDate;
while (!currentDate.isAfter(endDate)) {
dates.add(currentDate);
currentDate = currentDate.plusDays(1);
}
return dates;
}
/**
* 从当前时间"yyyy-MM-dd"格式获取上个月的时间
*/
public static Calendar getPreMonth(String startDate) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
Date date = format.parse(startDate);
c.setTime(date);
c.add(Calendar.MONTH, -1);
return c;
}
/**
* 两个时间比较返回大的那个时间
*/
public static Date getMaxDate(Date date1, Date date2) {
if (date1.getTime() > date2.getTime()) {
return date1;
} else {
return date2;
}
}
/**
* 两个时间比较返回小的那个时间
*/
public static Date getMinDate(Date date1, Date date2) {
if (date1.getTime() > date2.getTime()) {
return date2;
} else {
return date1;
}
}
/**
* 判断开始时间和结束时间中是否包含休息日,返回的为休息日的天数
*
* @param startTime
* @param endTime
* @param restDates
* @return
*/
public static Long getHolidayHours(LocalDate startTime, LocalDate endTime, Set<LocalDate> restDates) {
Set<LocalDate> datesInRange = new HashSet<>();
for (LocalDate date = startTime; !date.isAfter(endTime); date = date.plusDays(1)) {
datesInRange.add(date);
}
Set<LocalDate> holidaysInRange = new HashSet<>();
int numHolidays = 0;
for (LocalDate holiday : restDates) {
if (datesInRange.contains(holiday)) {
holidaysInRange.add(holiday);
numHolidays++;
}
}
return (long) numHolidays;
}
/**
* 判断当前天数是否在休息日里
*
* @param checkTime
* @param restTimes
* @return
*/
public static boolean isRestTime(LocalDate checkTime, Set<LocalDate> restTimes) {
if (restTimes.contains(checkTime)) {
// 在休息日时间范围内
return true;
} else {
// 不在休息日时间范围内
return false;
}
}
public static boolean isRestDay(LocalDate date, Set<LocalDate> restDays) {
DayOfWeek dayOfWeek = date.getDayOfWeek();
// 判断当前日期是否在休息日列表中
return restDays.contains(date) || dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY;
}
public static Set<LocalTime[]> getLocalDateTime(Set<LocalDate> dates) {
Set<LocalTime[]> timeSet = new HashSet<>();
for (LocalDate date : dates) {
LocalTime startTime = LocalTime.MIN;
LocalTime endTime = LocalTime.MAX;
LocalTime[] times = {startTime, endTime};
timeSet.add(times);
}
return timeSet;
}
public static Date getDate(String reCardTime) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
return format.parse(reCardTime);
}
/**
* long转为时间格式
*
* @param timestamp
* @param formate
* @return
*/
public static Date longToDate(Long timestamp, String formate) {
Date date = new Date(timestamp);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formate);
String format = simpleDateFormat.format(date);
try {
return simpleDateFormat.parse(format);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* 时间加法
*
* @param punchTime 打卡时间
* @param shiftPlanModel 获取最小的考勤开始的结束时间
* @param lateTime 晚走的时间
* @param lateArrival 弹性打卡
* @return 新的时间
*/
public static String timeAdd(Long punchTime, String shiftPlanModel, String lateTime, String lateArrival) {
//根据打卡时间获取年月日
Date date = new Date(punchTime);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd ");
String nyr = format.format(date);
String start = nyr + shiftPlanModel;
SimpleDateFormat hmFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
Date startDate = hmFormat.parse(start);
Calendar calendar = Calendar.getInstance();
int late = Integer.parseInt(lateTime) + Integer.parseInt(lateArrival);
calendar.setTime(startDate);
calendar.add(Calendar.MINUTE, late);
return hmFormat.format(calendar.getTime());
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* localDateTime 转为 date
*
* @param localDateTime
* @return
*/
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
return Date.from(zonedDateTime.toInstant());
}
/**
* Date转LocalDateTime
*/
public static LocalDateTime dateToLocalDateTime(Date date) {
// 将 Date 转换为 LocalDateTime
LocalDateTime dateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
return dateTime;
}
/**
* 将指定的年月日与时分拼接
*
* @param time1
* @param time2
* @return
* @throws ParseException
*/
public static Date dateToShiftDate(String time1, String time2) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd ");
Date date = format.parse(time1);
String format1 = format.format(date);
String newTime = format1 + time2;
return DateUtil.stringToDate(newTime, "yyyy-MM-dd HH:mm");
}
/**
* 截取考勤封存日期
*
* @param day
* @param executionTime
* @return
* @throws ParseException
*/
public static Date extracted(Integer day, String executionTime) throws ParseException {
LocalTime time = LocalTime.parse(executionTime);
// 从执行时间中获取时分秒
int hour = time.getHour();
int minute = time.getMinute();
int second = time.getSecond();
// 获取当前的年份和月份
int currentYear = LocalDate.now().getYear();
int currentMonth = LocalDate.now().getMonthValue();
// 根据年月和指定的日创建日期对象
// 使用指定的年月日和截取的时分秒创建新的执行时间
LocalDateTime newDateTime = LocalDateTime.of(LocalDate.of(currentYear, currentMonth, day), LocalTime.of(hour, minute, second));
Date from = Date.from(newDateTime.atZone(ZoneId.systemDefault()).toInstant());
return from;
}
public static Date splicingTime(Date date, String executionTime) throws ParseException {
LocalTime time = LocalTime.parse(executionTime);
// 从执行时间中获取时分秒
int hour = time.getHour();
int minute = time.getMinute();
int second = time.getSecond();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// 获取当前的年份和月份
// 获取年、月、日
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
// 根据年月和指定的日创建日期对象
// 使用指定的年月日和截取的时分秒创建新的执行时间
LocalDateTime newDateTime = LocalDateTime.of(LocalDate.of(year, month, day), LocalTime.of(hour, minute, second));
Date from = Date.from(newDateTime.atZone(ZoneId.systemDefault()).toInstant());
return from;
}
/**
* 计算两个时间之间的小时时差
*
* @param start
* @param end
* @return
*/
public static Long calculateHours(String start, String end) {
LocalTime startTime = LocalTime.parse(start);
LocalTime endTime = LocalTime.parse(end);
long hourDifference = ChronoUnit.HOURS.between(startTime, endTime);
System.out.println("小时差为:" + hourDifference + "小时");
return hourDifference;
}
public static Long dateAddAndSub(Date sourceDate, Date goal) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(sourceDate);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(goal);
long diff = calendar2.getTimeInMillis() - calendar1.getTimeInMillis();
long minutes = diff / (60 * 1000);
return minutes;
}
/**
* 判断时间是否跨天
*
* @param startTime
* @param endTime
* @return
*/
public static Boolean isSpanDay(Date startTime, Date endTime) {
Instant startInstant = startTime.toInstant();
Instant endInstant = endTime.toInstant();
// 使用指定时区(例如默认时区)创建LocalDateTime对象
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime dateTime1 = LocalDateTime.ofInstant(startInstant, zoneId);
LocalDateTime dateTime2 = LocalDateTime.ofInstant(endInstant, zoneId);
boolean isCrossDay = dateTime1.toLocalDate().isBefore(dateTime2.toLocalDate());
return isCrossDay;
}
/**
* 判断两个时间中是否还有多余的天数
*
* @param startTime
* @param endTime
* @return
*/
public static long getDays(Date startTime, Date endTime) {
Instant startInstant = startTime.toInstant();
Instant endInstant = endTime.toInstant();
// 使用指定时区(例如默认时区)创建LocalDateTime对象
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime dateTime1 = LocalDateTime.ofInstant(startInstant, zoneId);
LocalDateTime dateTime2 = LocalDateTime.ofInstant(endInstant, zoneId);
long days = ChronoUnit.DAYS.between(dateTime1.toLocalDate(), dateTime2.toLocalDate());
System.out.println(days);
if (days > 0) {
long additionalDays = days - 1;
return additionalDays;
} else {
return 0;
}
}
/**
* 检查日期是否合法
*
* @param dayOfMonth 一个月中的某一天
* @return 检查结果
*/
public static boolean checkDayOfMonthIsValid(String dayOfMonth) {
String concatDate = LocalDate.now().getYear() + StrPool.DASHED + dayOfMonth;
try {
//将传入的日期字符串解析为LocalDate对象
LocalDate.parse(concatDate, DateTimeFormatter.ofPattern("uuuu-MM-dd")
.withResolverStyle(ResolverStyle.STRICT));
} catch (Exception e) {
//捕获DateTimeException异常,表示日期不合法
return false;
}
return true;
}
/**
* 获取对应月份上个月的时间
*
* @param date
* @return
*/
public static LocalDateTime getLastMonth(Date date) {
LocalDateTime localDateTime = DateUtil.dateToLocalDateTime(date);
LocalDateTime lastMonth = localDateTime.minusMonths(1);
return lastMonth;
}
/**
* 检查格式为yyyy-MM-dd的日期是否合法。
*
* @param str 日期字符串
* @return 合法true 不合法false
*/
public static boolean checkDate(String str) {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");//括号内为日期格式,y代表年份,M代表年份中的月份(为避免与小时中的分钟数m冲突,此处用M),d代表月份中的天数
try {
sd.setLenient(false);//此处指定日期/时间解析是否不严格,在true是不严格,false时为严格
sd.parse(str);//从给定字符串的开始解析文本,以生成一个日期
} catch (Exception e) {
return false;
}
return true;
}
}
package com.scggic.hr.service.ov.common;标签:return,String,param,时间,关于,Date,static,工具,public From: https://www.cnblogs.com/yangkailina/p/17651793.html
import com.scggic.hr.service.utils.DateUtil;
import lombok.Data;
import java.util.Date;
/**
* @Name: DateVo
* @Author: WTQ
* @Date: 2023/4/11 15:15
* @Version: 1.0
* @Description:
*/
@Data
public class DateVo {
private String START_TIME = " 00:00:00";
private String END_TIME = " 23:59:59";
public void setBeginDate(Date beginDate) {
this.beginDate = beginDate;
this.beginDateStr = DateUtil.getDateStr(beginDate) + START_TIME;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
this.endDateStr = DateUtil.getDateStr(endDate) + END_TIME;
}
//开始时间
private Date beginDate;
//结束时间
private Date endDate;
private String beginDateStr;
private String endDateStr;
}