时间工具类,包括JDK8的时间相关的API包装、Date类与新的JDK8实践类的转换、打印格式、判断条件等;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
/**
* @Description 日期工具类
*/
public class DateUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(DateUtil.class);
public static final String DATE_FORMAT_1 = "yyyy-MM-dd";
public static final String DATE_FORMAT_2 = "yyyyMMdd";
public static final String DATE_FORMAT_3 = "yyyy年MM月dd日";
public static final String DATE_FORMAT_4 = "yyyy/MM/dd";
public static final String DATE_FORMAT_5 = "yyyy.MM.dd";
public static final String DATE_FORMAT_6 = "yyyy年MM月";
public static final String DATE_FORMAT_7 = "yyyy.M.d";
public static final String DATETIME_FORMAT_1 = "yyyy-MM-dd HH:mm:ss";
public static final String DATETIME_FORMAT_3 = "yyyy-MM-dd HH-mm-ss";
public static final String DATETIME_FORMAT_2 = "yyyyMMddHHmmss";
public static final String DATETIME_FORMAT_4 = "yyyy/MM/dd HH:mm:ss";
public static final String DATETIME_FORMAT_5 = "yyyy-MM-dd HH:mm";
public static final String MONTH_FORMAT_1 = "M月d日";
public static final String MONTH_FORMAT_2 = "MM-dd";
public static final String MONTH_FORMAT_3 = "M月d日 HH点";
public static final String MONTH_FORMAT_4 = "M月d日 HH:mm";
public static final int DIFFER_IN_SECOND = 0;
public static final int DIFFER_IN_MINUTE = 1;
public static final int DIFFER_IN_HOUR = 2;
public static final int DIFFER_IN_DAY = 3;
public static final String DEF_DATE_FORMAT = DATETIME_FORMAT_1;
public static final String DEF_DATE_FORMAT_SHORT = DATE_FORMAT_1;
private DateUtil() {
throw new IllegalStateException("Utility class");
}
public static Date toDate(String str) {
try {
if (StringUtils.isNotEmpty(str) && str.indexOf(' ') == -1) {
str += " 00:00:00";
}
SimpleDateFormat sdf = new SimpleDateFormat(DEF_DATE_FORMAT);
return sdf.parse(str);
} catch (Exception e) {
return null;
}
}
public static String toString(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(DEF_DATE_FORMAT);
return sdf.format(date);
}
public static String toShortString(Date date) {
return toStringByFormat(date, DEF_DATE_FORMAT_SHORT);
}
public static String toStringByFormat(Date date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
public static Date getDate(int addDay) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, addDay);
return calendar.getTime();
}
public static Date getToday(String format) {
SimpleDateFormat sdf = getDateFormat(format);
try {
return sdf.parse(sdf.format(new Date()));
} catch (ParseException e) {
LOGGER.error("获取当天日期异常", e);
}
return new Date();
}
public static Date getDate(Date date, int addDay) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, addDay);
return calendar.getTime();
}
public static Date getDate(int type, int add) {
Calendar calendar = Calendar.getInstance();
calendar.add(type, add);
return calendar.getTime();
}
public static Integer leftDay(Date pEndDate) {
Calendar startDate = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
if (pEndDate != null) {
endDate.setTime(pEndDate);
}
return betweenDay(startDate, endDate);
}
public static Integer betweenDay(Date startDate, Date endDate) {
Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);
return betweenDay(start, end);
}
public static Integer betweenDay(Calendar startDate, Calendar endDate) {
Calendar start = (Calendar) startDate.clone();
Calendar end = (Calendar) endDate.clone();
Integer daysBetween = 0;
start.set(Calendar.HOUR_OF_DAY, 0);
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MILLISECOND, 0);
end.set(Calendar.HOUR_OF_DAY, 0);
end.set(Calendar.MINUTE, 0);
end.set(Calendar.SECOND, 0);
end.set(Calendar.MILLISECOND, 0);
if (start.before(end)) {
while (start.before(end)) {
start.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
} else {
while (start.after(end)) {
start.add(Calendar.DAY_OF_MONTH, -1);
daysBetween--;
}
}
return daysBetween;
}
/**
* Description: 将日期转为字符串 <br>
*
* @param date <br>
* @param format 转换格式,DateUtil中有 <br>
* @return <br>
*/
public static String date2String(Date date, String format) {
if (date == null) {
return "";
}
SimpleDateFormat sdf = getDateFormat(format);
return sdf.format(date);
}
/**
* Description: 根据日期格式化字符串生成日期格式化对象 <br>
*
* @param format
* @return <br>
*/
public static SimpleDateFormat getDateFormat(String format) {
return new SimpleDateFormat(format);
}
/**
* Description: 将字符串转为日期对象,自动判断几种常见的日期格式 <br>
*
* @param date
* @return <br>
*/
public static Date string2Date(String date) {
Date ret = null;
if (date == null || date.length() == 0) {
return ret;
}
if (date.length() > 11) {
if (date.indexOf('-') > -1) {
if (date.indexOf(':') > -1) {
ret = string2Date(date, DATETIME_FORMAT_1);
} else {
ret = string2Date(date, DATETIME_FORMAT_3);
}
} else if (date.indexOf('/') > -1) {
ret = string2Date(date, DATETIME_FORMAT_4);
} else {
ret = string2Date(date, DATETIME_FORMAT_2);
}
} else {
if (date.indexOf('-') > -1) {
ret = string2Date(date, DATE_FORMAT_1);
} else if (date.indexOf('/') > -1) {
ret = string2Date(date, DATE_FORMAT_4);
} else if (date.length() == 8) {
if (date.endsWith("d")) {
ret = string2Date(date, DATE_FORMAT_2);
} else {
ret = string2Date(date, DATE_FORMAT_6);
}
} else {
ret = string2Date(date, DATE_FORMAT_3);
}
}
return ret;
}
/**
* Description: 将字符串转为日期对象,需要输入转换格式 <br>
*
* @param date
* @param format
* @return <br>
*/
public static Date string2Date(String date, String format) {
if (StringUtils.isEmpty(date)) {
return null;
}
if (!ValidateUtil.validateNotEmpty(format)) {
throw new IllegalArgumentException("日期格式化字符串为空");
}
SimpleDateFormat sdf = getDateFormat(format);
if (!ValidateUtil.validateNotNull(sdf)) {
throw new IllegalArgumentException("日期格式化字符串不能匹配到日期格式化对象,请检查格式是否正确");
}
try {
return sdf.parse(date);
} catch (ParseException e) {
throw new IllegalArgumentException("日期字符串 " + date + " 和日期格式化字符串不匹配 " + format, e);
}
}
/**
* Description: 获取N秒偏移后的时间,不考虑夏时令 <br>
*
* @param date
* @param seconds
* @return <br>
*/
public static Date offsetSecond(Date date, long seconds) {
if (date == null) {
return null;
}
long time = date.getTime();
long time2 = time + (seconds * 1000);
Date date2 = new Date(time2);
return date2;
}
/**
* Description: 获取N分钟偏移后的时间 <br>
*
* @param date
* @param minutes
* @return <br>
*/
public static Date offsetMinute(Date date, long minutes) {
return offsetSecond(date, 60 * minutes);
}
/**
* Description: 获取N小时偏移后的时间 <br>
*
* @param date
* @param hours
* @return <br>
*/
public static Date offsetHour(Date date, long hours) {
return offsetMinute(date, 60 * hours);
}
/**
* @param date
* @param days
* @return <br>
* @Description: 获取N天偏移后的时间 <br>
*/
public static Date offsetDay(Date date, int days) {
return offsetHour(date, 24L * days);
}
/**
* @param date
* @param weeks
* @return <br>
* @Description: 获取N周偏移后的时间 <br>
*/
public static Date offsetWeek(Date date, int weeks) {
return offsetDay(date, 7 * weeks);
}
/**
* @param date1
* @param ,months
* @return <br>
* @Description: 获取N月偏移后的时间 <br>
*/
public static Date offsetMonth(Date date1, int months) {
if (date1 == null) {
return null;
}
Date date = new Date(date1.getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int curDay = calendar.get(Calendar.DAY_OF_MONTH);
int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.MONTH, months);
int newMaxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
if (curDay == maxDay) {
calendar.set(Calendar.DAY_OF_MONTH, newMaxDay);
} else {
if (curDay > newMaxDay) {
calendar.set(Calendar.DAY_OF_MONTH, newMaxDay);
} else {
calendar.set(Calendar.DAY_OF_MONTH, curDay);
}
}
date.setTime(calendar.getTimeInMillis());
return date;
}
/**
* Description: 获取N年偏移后的时间 <br>
*
* @param date
* @param years
* @return <br>
*/
public static Date offsetYear(Date date, int years) {
if (date == null) {
return null;
}
Date newdate = (Date) date.clone();
Calendar calendar = Calendar.getInstance();
calendar.setTime(newdate);
calendar.add(Calendar.YEAR, years);
newdate.setTime(calendar.getTimeInMillis());
return newdate;
}
/**
* Description: 当天的最后一秒 <br>
*
* @param date
* @return <br>
*/
public static Date getLastSecondOfDate(Date date) {
Date newdate = (Date) date.clone();
Calendar calendar = Calendar.getInstance();
calendar.setTime(newdate);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
newdate.setTime(calendar.getTimeInMillis());
return newdate;
}
/**
* Description: 当天的第一秒 <br>
*
* @param date
* @return <br>
*/
public static Date getFirstSecondOfDate(Date date) {
Date newdate = (Date) date.clone();
Calendar calendar = Calendar.getInstance();
calendar.setTime(newdate);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
newdate.setTime(calendar.getTimeInMillis());
return newdate;
}
/**
* Description: 当星期的最后一秒<br>
*
* @param date
* @return <br>
* @author chenhaitong<br>
*/
public static Date getLastSecondOfWeek(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
Date tmp = new Date();
tmp.setTime(calendar.getTimeInMillis());
return tmp;
}
public static Date getFirstSecondOfWeek(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
Date tmp = new Date();
tmp.setTime(calendar.getTimeInMillis());
return tmp;
}
/**
* Description: 比较两个时间之间的差值 <br>
*
* @param beginDate
* @param endDate
* @param returnType 返回的类型 0:秒 1:分钟 2:小时 3:天
* @return
*/
public static long differDateInDays(Date beginDate, Date endDate, int returnType) {
long begin = beginDate.getTime();
long end = endDate.getTime();
long surplus = begin - end;
Calendar calendarBeginDate = Calendar.getInstance();
calendarBeginDate.setTime(beginDate);
Calendar calendarEndDate = Calendar.getInstance();
calendarEndDate.setTime(endDate);
long ret = 0;
switch (returnType) {
case DIFFER_IN_SECOND:
ret = surplus / 1000;
break;
case DIFFER_IN_MINUTE:
ret = surplus / 1000 / 60;
break;
case DIFFER_IN_HOUR:
ret = surplus / 1000 / 60 / 60;
break;
case DIFFER_IN_DAY:
ret = surplus / 1000 / 60 / 60 / 24;
break;
default:
ret = surplus;// 增加毫秒级计算结果
break;
}
return ret;
}
/**
* Description: 检测某个时间是否在一个时间段范围内,参数为日期类型 <br>
*
* @param date
* @param beginDate
* @param endDate
* @return <br>
*/
public static boolean isInRange(Date date, Date beginDate, Date endDate) {
long time = date.getTime();
long beginTime = beginDate.getTime();
long endTime = endDate.getTime();
if (time >= beginTime && time <= endTime) {
return true;
} else {
return false;
}
}
public static Boolean isToday(Date when) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
if (calendar.before(when)) {
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
if (calendar.after(when)) {
return true;
}
}
return false;
}
/**
* Description:比较两个时间大小 <br>
*
* @param firstStr
* @param secondStr
* @return true:开始时间小于结束时间 false:开始时间小于等于结束时间 <br>
*/
private static boolean isAsc(String firstStr, String secondStr) {
return firstStr.compareTo(secondStr) < 0;
}
public static boolean isSameDay(Date source, Date target) {
return isInRange(target, getFirstSecondOfDate(source), getLastSecondOfDate(source));
}
public static boolean isBeforeNow(Date date) {
if (date == null) {
return false;
}
Date now = new Date();
return date.before(now);
}
public static LocalDateTime asLocalDateTime(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
public static LocalDate asLocalDate(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}
public static long getRemainSecondsOfDay() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime midnight = now.plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
long seconds = ChronoUnit.SECONDS.between(now, midnight);
return seconds;
}
public static Date getOffsetDay(int offset) {
LocalDate offsetDay = LocalDate.now().plusDays(offset);
return Date.from(offsetDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
}
public static Date getOffsetDay(LocalDate base, int offset) {
LocalDate offsetDay = base.plusDays(offset);
return Date.from(offsetDay.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
public static Date getEndTimeOfYesterday(LocalDate base) {
Instant instant = base.atStartOfDay(ZoneId.systemDefault()).toInstant().minusSeconds(1L);
return Date.from(instant);
}
public static boolean isTheSameDay(Date a, Date b) {
LocalDateTime aLocalDateTime = asLocalDateTime(a);
LocalDateTime bLocalDateTime = asLocalDateTime(b);
if (aLocalDateTime.toLocalDate().toEpochDay() == bLocalDateTime.toLocalDate().toEpochDay()) {
return true;
}
return false;
}
/**
* Date to LocalDate
*
* @param date
* @return
*/
public static LocalDate toLocalDate(Date date) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
public static Date localDate2Date(LocalDate localDate) {
if (null == localDate) {
return null;
}
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
return Date.from(zonedDateTime.toInstant());
}
/**
* Date时间戳转成MySQL的DATE类型
*
* @param timestamp
* @return
*/
public static java.sql.Date toSQLDate(Date timestamp) {
if (timestamp != null) {
return new java.sql.Date(timestamp.getTime());
}
return null;
}
}