package com.smy.framework.core.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;
/**
*
* 类说明:日期工具类
*
*
* 详细描述:
*
* @author youlu
* @since 2022-5-5
*/
public class DateUtil {
public final static String DATE_FROMAT_YYYYMMDD = "yyyyMMdd";
public final static String DATE_FROMAT_YYMMDD = "yyMMdd";
public final static String TIME_FORMAT_HHMMSS = "HHmmss";
/**
* 两个日期是否在跨度之内
*
* @param startDate
* @param endDate
* @param gapType
* 跨度类型,如Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_YEAR
* @param maxGap
* 最大跨度值
* @return
*/
public static boolean isWithInDateGap(Date startDate, Date endDate,
int gapType, int maxGap) {
if (startDate == null) {
throw new IllegalArgumentException("The startDate must not be null");
}
if (endDate == null) {
throw new IllegalArgumentException("The endDate must not be null");
}
if (gapType != Calendar.YEAR && gapType != Calendar.MONTH
&& gapType != Calendar.DAY_OF_YEAR) {
throw new IllegalArgumentException(
"The value of gapType is invalid");
}
Calendar start = Calendar.getInstance();
start.setTime(startDate);
start.add(gapType, maxGap);
int compare = start.getTime().compareTo(endDate);
return compare >= 0;
}
/**
* 两个日期是否在跨度之内
*
* @param startDate
* @param endDate
* @param gapType
* 跨度类型,如Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_YEAR
* @param maxGap
* 最大跨度值
* @return
* @throws ParseException
*/
public static boolean isWithInDateGap(String startDate, String endDate,
int gapType, int maxGap){
Date startDateTime = null;
Date endDateTime = null;
try{
startDateTime = DateUtils.parseDate(startDate, DATE_FROMAT_YYYYMMDD);
endDateTime = DateUtils.parseDate(endDate, DATE_FROMAT_YYYYMMDD);
}catch(ParseException e){
throw new IllegalArgumentException("日期格式错误,开始日期:" + startDate + ",结束日期:" + endDate,e);
}
return isWithInDateGap(startDateTime,endDateTime, gapType, maxGap);
}
/**
* 两个日期是否在跨度之内
*
* @param startDate
* @param endDate
* @param gapType
* 跨度类型,如Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_YEAR
* @param maxGap
* 最大跨度值
* @return
* @throws ParseException
*/
public static boolean isWithInDateGap(int startDate, int endDate,
int gapType, int maxGap) throws ParseException {
return isWithInDateGap(
DateUtils.parseDate(String.valueOf(startDate), DATE_FROMAT_YYYYMMDD),
DateUtils.parseDate(String.valueOf(endDate), DATE_FROMAT_YYYYMMDD),
gapType, maxGap);
}
/**
* 说明: 获取系统当前日期
*
* @param
* @return
* @
* @since 2014年5月22日
*/
public static int getCurIntDate() {
return Integer.parseInt(getCurStringDate());
}
/**
* 说明: 获取系统当前日期
*
* @param
* @return
* @
* @since 2014年5月22日
*/
public static String getCurStringDate() {
java.util.Date currentDate = new java.util.Date();
SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT_YYYYMMDD);
return formatdate.format(currentDate);
}
/***
* 说明: 获取指定格式的系统当前日期
* @param
* @return
* @
* @since 2014年5月26日
*/
public static String getCurDate(String strFormat)
{
java.util.Date currentDate = new java.util.Date();
SimpleDateFormat formatdate = new SimpleDateFormat(strFormat);
return formatdate.format(currentDate);
}
/***
* 说明: 获取当时系统日期时间【YYYYMMDDHHmmss】
* @param
* @return
* @since 2014年6月5日
*/
public static String getCurStringDateTime()
{
java.util.Date currentDate = new java.util.Date();
SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT_YYYYMMDD+TIME_FORMAT_HHMMSS);
return formatdate.format(currentDate);
}
/**
* 说明: 获取当时系统日期时间【YYYYMMDDHHmmss】
* @param
* @return
* @since 2014年6月5日
*/
public static Long getIntCurIntDateTime()
{
return Long.valueOf(getCurStringDateTime());
}
/**
* 说明: 获取系统当前时间
*
* @param
* @return 当前时间并格式化成“HHmmss”,如“123124”
* @
* @since 2014年5月22日
*/
public static String getCurTime() {
java.util.Date currentDate = new java.util.Date();
SimpleDateFormat formatdate = new SimpleDateFormat(TIME_FORMAT_HHMMSS);
return formatdate.format(currentDate);
}
/**
* 说明: 验证传入数值型日期[YYYYMMDD]是否合法
*
* @param
* @return
* @
* @return
* @since 2014年5月22日
*/
public static boolean checkDateFormat(int intDate) {
return checkDateFormat(String.valueOf(intDate));
}
/**
* 说明: 验证传入字符型日期[YYYYMMDD]是否合法
*
* @param
* @return
* @
* @since 2014年5月22日
*/
public static boolean checkDateFormat(String strDate) {
return checkDateFormat(strDate, DATE_FROMAT_YYYYMMDD);
}
/**
* 说明: 验证传入字符型日期是否合法
*
* @param
* @return
* @
* @since 2014年5月22日
*/
public static boolean checkDateFormat(int intDate, String strFormat) {
return checkDateFormat(String.valueOf(intDate), DATE_FROMAT_YYYYMMDD);
}
/**
* 说明: 验证传入字符型日期是否合法
*
* @param
* @return
* @
* @since 2014年5月22日
*/
public static boolean checkDateFormat(String strDate, String strFormat)
{
try {
DateUtils.parseDateStrictly(strDate, strFormat);
return true;
} catch (ParseException e) {
return false;
}
}
/**
* 说明: 验证传入字符型时间[HH24MMSS]是否合法
*
* @param
* @return
* @
* @since 2014年5月22日
*/
public static boolean checkTimeFormat(String strDate) {
return checkTimeFormat(strDate, TIME_FORMAT_HHMMSS);
}
/**
* 说明: 验证传入字符型时间是否合法
*
* @param
* @return
* @
* @since 2014年5月22日
*/
public static boolean checkTimeFormat(int intDate, String strFormat) {
return checkTimeFormat(String.valueOf(intDate), DATE_FROMAT_YYYYMMDD);
}
/**
* 说明: 验证传入字符型时间是否合法
*
* @param
* @return
* @
* @since 2014年5月22日
*/
public static boolean checkTimeFormat(String strDate, String strFormat){
try {
DateUtils.parseDateStrictly(strDate, strFormat);
return true;
} catch (ParseException e) {
return false;
}
}
/**
* 说明: 日期转换
* @param strDate
* @return
*/
public static Date parseDate(String strDate){
return parseDate(strDate, DATE_FROMAT_YYYYMMDD);
}
/**
* 说明: 日期转换
* @param strDate
* @param strFormat
* @return
*/
public static Date parseDate(String strDate,String strFormat){
try {
return DateUtils.parseDateStrictly(strDate, strFormat);
} catch (ParseException e) {
throw new IllegalArgumentException("日期格式错误,日期:" + strDate,e);
}
}
/**
* 说明: 日期转换
* @param intDate
* @param strFormat
* @return
*/
public static Date parseDate(int intDate,String strFormat){
return parseDate(String.valueOf(intDate), strFormat);
}
/**
* 说明: 日期转换
* @param intDate
* @return
*/
public static Date parseDate(int intDate){
return parseDate(String.valueOf(intDate));
}
/**
* 日期转换成字符串
* @param date
* @param dateFormat
* @return
*/
public static String date2String(Date date,String dateFormat) {
SimpleDateFormat formatdate = new SimpleDateFormat(dateFormat);
return formatdate.format(date);
}
/**
* 时间戳转换成字符串
* @param date
* @param dateFormat
* @return
*/
public static String timestamp2String(long date,String dateFormat) {
SimpleDateFormat formatdate = new SimpleDateFormat(dateFormat);
return formatdate.format(date);
}
/**
* 日期转换成字符串
* @param date
* @param dateFormat
* @return 格式为YYYYMMDD
*/
public static String date2String(Date date) {
return date2String(date,DATE_FROMAT_YYYYMMDD);
}
/**
* 日期转换成整数
* @param date
* @param dateFormat
* @return 格式为YYYYMMDD
*/
public static int date2Int(Date date) {
String str = date2String(date,DATE_FROMAT_YYYYMMDD);
return Integer.parseInt(str);
}
/**
* 获取指定日期之前的相隔天数的日期
* @param inputDate 日期
* @param days 天数
* @return
* @since 2014年7月1日
*/
public static Integer getDateBeforeDay(Integer inputDate,int days){
Calendar theCa = Calendar.getInstance();
theCa.setTime(parseDate(inputDate));
theCa.add(Calendar.DATE, -1*days);
Date date = theCa.getTime();
SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT_YYYYMMDD);
return Integer.valueOf(formatdate.format(date));
}
/**
* 获取指定日期之后的相隔n年的日期
* @param inputDate
* @param years
* @return
* @return Integer
*/
public static Integer getDateAfterYear(Integer inputDate, int years) {
Calendar theCa = Calendar.getInstance();
theCa.setTime(parseDate(inputDate));
theCa.add(Calendar.YEAR, years);
Date date = theCa.getTime();
SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT_YYYYMMDD);
return Integer.valueOf(formatdate.format(date));
}
/**
* 获取指定日期之后的相隔天数的日期
* @param date 日期
* @param days 天数
* @return
* @since 2014年7月1日
*/
public static Integer getDateAfterDay(Integer date,int days){
Calendar theCa = Calendar.getInstance();
theCa.setTime(parseDate(date));
theCa.add(Calendar.DATE, 1*days);
Date tempdate = theCa.getTime();
SimpleDateFormat formatdate = new SimpleDateFormat(DATE_FROMAT_YYYYMMDD);
return Integer.valueOf(formatdate.format(tempdate));
}
}
package com.smy.scs.util;
import com.smy.framework.core.util.DateUtil;
import com.smy.scs.constants.ApplyConstants;
import org.joda.time.*;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class DateUtils extends DateUtil {
private static final String SHORT_DATE_FORMATE = "yyMMdd";
public final static String COMMON_DATE_FORMAT = "yyyyMMdd";
public final static String SLASH_DATE_FORMAT = "yyyy/MM/dd";
/**
* 根据出生日期计算年龄
*
* @param birthday String类型,格式如:19851221
* @return
*/
public static String getAgeByBirthday(Integer birthday) {
if (null == birthday) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date birthDate = null;
try {
birthDate = sdf.parse(String.valueOf(birthday));
} catch (ParseException e) {
e.printStackTrace();
return null;
}
Calendar cal = Calendar.getInstance();
if (cal.before(birthday)) {
throw new IllegalArgumentException(
"The birthDay is before Now.It's unbelievable!");
}
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH) + 1;
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDate);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH) + 1;
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
int age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
// monthNow==monthBirth
if (dayOfMonthNow < dayOfMonthBirth) {
age--;
}
} else {
// monthNow>monthBirth
age--;
}
}
return String.valueOf(age);
}
/**
* 获取+几个月后的日期
*
* @param month
* @return
*/
public static String getDateForAddMonth(int month) {
GregorianCalendar gc = new GregorianCalendar();
try {
gc.setTime(new Date());
gc.add(2, +month);
} catch (Exception e) {
}
return new SimpleDateFormat("yyyyMMdd").format(gc.getTime()).toString();
}
/**
* 计算时间大小
* DATE1 < DATE2 = -1
* DATE1 = DATE2 = 0
* DATE1 > DATE2 = 1
*
* @param DATE1
* @param DATE2
* @return
*/
public static int compare_date(String DATE1, String DATE2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
if (dt1.getTime() > dt2.getTime()) {
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 根据时间获取案件自动通过rediskey
*
* @param dataNow
* @return
* @throws ParseException
*/
@SuppressWarnings("static-access")
public static String getApplyAutoPassCountKey() {
StringBuffer key = new StringBuffer("crs.ApplyAutoPassCount");
Date date = new Date();
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
String nowDateStr1 = df1.format(date) + " 06:00:00";
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nowDateStr = df2.format(date);
//昨天的日期
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(calendar.DATE, -1);// 把日期往后增加一天.整数往后推,负数往前移动
Date preDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
String preDateStrKey = new SimpleDateFormat("yyyyMMdd").format(preDate);
String nowDateStrKey = new SimpleDateFormat("yyyyMMdd").format(date);
int i = compare_date(nowDateStr1, nowDateStr);
if (i <= 0) {
//新的key
key.append(nowDateStrKey);
} else {
//昨天的Key
key.append(preDateStrKey);
}
return key.toString();
}
/**
* 两个时间相差距离多少天多少小时多少分多少秒
*
* @param str1 时间参数 1 格式:19900101120000
* @param str2 时间参数 2 格式:20090101120000
* @return String 返回值为:xx天xx小时xx分xx秒
*/
public static String getDistanceTime(String str1, String str2) {
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
Date one;
Date two;
long day = 0;
long hour = 0;
long min = 0;
long sec = 0;
try {
one = df.parse(str1);
two = df.parse(str2);
long time1 = one.getTime();
long time2 = two.getTime();
long diff;
if (time1 < time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
day = diff / (24 * 60 * 60 * 1000);
hour = (diff / (60 * 60 * 1000) - day * 24);
min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
} catch (ParseException e) {
e.printStackTrace();
}
return day + "天" + hour + "小时" + min + "分" + sec + "秒";
}
/**
* 判断是否超过24小时
*
* @param startDateTime 时间参数 1 格式:19900101120000
* @param endDateTime 时间参数 2 格式:20090101120000
* @return
*/
public static boolean judgeDateGreaterThan24h(String startDateTime, String endDateTime) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date start = sdf.parse(startDateTime);
Date end = sdf.parse(endDateTime);
long cha = end.getTime() - start.getTime();
double result = cha * 1.0 / (1000 * 60 * 60);
if (result < 24) {
return false;
} else {
return true;
}
} catch (Exception e) {
// TODO: handle exception
}
return false;
}
/**
* 计算两个时间差,返回分钟数
*
* @param startDateTime
* @param endDateTime
* @return
*/
public static int getDeltaTime(String startDateTime, String endDateTime) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date compareTime;
Date currentTime;
long minutes = 0;
try {
compareTime = sdf.parse(startDateTime);
currentTime = sdf.parse(endDateTime);
long diff = currentTime.getTime() - compareTime.getTime();
minutes = (diff) / (1000 * 60);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new Long(minutes).intValue();
}
/**
* 获取日
*
* @param time
* @return
*/
public static int getDay(Date time) {
if (time == null) {
return -1;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
return calendar.get(Calendar.DAY_OF_MONTH);
}
/**
* 获取日
*
* @return
*/
public static int getDay() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
return calendar.get(Calendar.DAY_OF_MONTH);
}
@SuppressWarnings("deprecation")
public static int getHour(Date d) {
int hours = d.getHours();
return hours;
}
public static String simple(Date date) {
if (null == date)
return "";
return new SimpleDateFormat("yyyyMMdd").format(date);
}
public static void main(String[] args) {
System.out.print(getHour(new Date()));
}
//获取系统时间并返回时间格式
public static Date currentDate() {
DateFormat YYYY_MM_DD_MM_HH_SS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String currentDates = YYYY_MM_DD_MM_HH_SS.format(new Date());
return YYYY_MM_DD_MM_HH_SS.parse(currentDates);
} catch (ParseException e) {
return new Date();
}
}
public static Date strToYYMMDDDate(String dateString) {
if (null == dateString)
return new Date();
try {
return new SimpleDateFormat("yyyyMMdd").parse(dateString);
} catch (ParseException e) {
return new Date();
}
}
/**
* 日期加上天数的时间
*
* @param date
* @param month
* @return
*/
public static Date dateAddDay(Date date, int day) {
return add(date, Calendar.DAY_OF_YEAR, day);
}
public static Date addMonth(Date date, int month) {
return add(date, Calendar.MONTH, month);
}
private static Date add(Date date, int type, int value) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(type, value);
return calendar.getTime();
}
/**
* 计算两个日期之间相差的天数
*
* @param smdate 较小的时间
* @param bdate 较大的时间
* @return 相差天数
* @throws ParseException
*/
public static int daysBetween(Date smdate, Date bdate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
smdate = sdf.parse(sdf.format(smdate));
} catch (ParseException e) {
e.printStackTrace();
}
try {
bdate = sdf.parse(sdf.format(bdate));
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(smdate);
long time1 = cal.getTimeInMillis();
cal.setTime(bdate);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
}
public static int getYear() {
Calendar ca = Calendar.getInstance();
int year = ca.get(Calendar.YEAR);//获取年份
return year;
}
/**
* 计算两个时间差,返回秒数
*
* @param startDate
* @param endDate
* @return
*/
public static int getDeltaTimeInSeconds(Date startDate, Date endDate) {
long senconds = 0;
long diff = endDate.getTime() - endDate.getTime();
senconds = (diff) / (1000);
return new Long(senconds).intValue();
}
/**
* 1.format date to common date format
* 2.thread safe
*
* @param date
* @return
*/
public static String formatDateCommon(Date date) {
return new DateTime(date).toString(COMMON_DATE_FORMAT);
}
public static String formatDateWithSlash(Date date) {
return new DateTime(date).toString(SLASH_DATE_FORMAT);
}
public static String caculateAgeWithShortFormat(String birthDate) {
return caculateAgeWithFormat(birthDate, DateTimeFormat.forPattern(SHORT_DATE_FORMATE));
}
public static String caculateAgeWithFullFormat(String birthDate) {
return caculateAgeWithFormat(birthDate, DateTimeFormat.forPattern(COMMON_DATE_FORMAT));
}
private static String caculateAgeWithFormat(String birthDate, DateTimeFormatter format) {
LocalDateTime birthday = LocalDateTime.parse(birthDate, format);
LocalDateTime now = new LocalDateTime(DateTimeZone.getDefault());
Years age = Years.yearsBetween(birthday, now);
return age.getYears() + "";
}
public static boolean isOverTimeWithinDuration(Date startDate, int durationDays) {
LocalDateTime startLocalDate = new LocalDateTime(startDate.getTime(), DateTimeZone.getDefault());
LocalDateTime now = new LocalDateTime(DateTimeZone.getDefault());
Days days = Days.daysBetween(startLocalDate, now);
if (days.getDays() >= durationDays) {
return true;
}
return false;
}
public static boolean isOverTimeWithinDurationHour(Date startDate, int durationHours) {
LocalDateTime startLocalDate = new LocalDateTime(startDate, DateTimeZone.getDefault());
LocalDateTime now = new LocalDateTime(DateTimeZone.getDefault());
Hours hours = Hours.hoursBetween(startLocalDate, now);
if (hours.getHours() >= durationHours) {
return true;
}
return false;
}
public static Date parseStandardDate(String dateString) {
DateTime dateTime = DateTime.parse(dateString, DateTimeFormat.forPattern(ApplyConstants.STANDARD_DATE_FORMATE));
dateTime.withZone(DateTimeZone.getDefault());
return new Date(dateTime.getMillis());
}
/**
* 获取零点日期
*
* @param date
* @return 1999-12-3 00:00:00
*/
public static Date getDayStart(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
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.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 获取23:59:59点日期
*
* @param date
* @return 1999-12-3 23:59:59
*/
public static Date getDayEnd(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTime();
}
}
使用hutool中的util的工具类,得到的是hutool自己实现的DateTime,它继承了原生的Date。
但是有些场景下,我们必须使用java原生util包下的Date,否则踩坑。可以用如下方法转换:
DateTime beforeDate = DateUtil.offsetDay(DateUtil.beginOfDay(new Date()), -7);
Calendar calendar = Calendar.getInstance();
calendar.setTime(beforeDate);
Date time = calendar.getTime();