package cn.huge.base.common.utils; import org.apache.commons.lang3.StringUtils; import java.text.SimpleDateFormat; import java.util.*; /** * @title: 时间工具类 * @description: 时间工具类 * @company: hugeinfo * @author: liyj * @time: 2021-11-05 16:51:48 * @version: 1.0.0 */ public class DateUtils { public static void main(String[] args) { } /** * 各时间格式 */ public static String YYYY_MM_DD_HH_MM_SS ="yyyy-MM-dd HH:mm:ss"; public static String YYYY_MM_DD_HH_MM ="yyyy-MM-dd HH:mm"; public static String YYYY_MM_DD ="yyyy-MM-dd"; public static String HH_MM_SS ="HH:mm:ss"; public static String YYYYMMDD ="yyyyMMdd"; private static String DATE_FORMAT_1 = "yyyy.MM.dd"; private static String DATE_FORMAT_2 = "yyyy/MM/dd"; private static String DATE_FORMAT_3 = "yyyy-MM"; private static String DATE_FORMAT_4 = "yyyy.MM"; private static String DATE_FORMAT_5 = "yyyy/MM"; /** * 时间格式枚举 */ enum DateStyle { MM_DD("MM-dd"), YYYY_MM("yyyy-MM"), YYYY_MM_DD("yyyy-MM-dd"), MM_DD_HH_MM("MM-dd HH:mm"), MM_DD_HH_MM_SS("MM-dd HH:mm:ss"), YYYY_MM_DD_HH_MM("yyyy-MM-dd HH:mm"), YYYY_MM_DD_HH_MM_SS("yyyy-MM-dd HH:mm:ss"), MM_DD_EN("MM/dd"), YYYY_MM_EN("yyyy/MM"), YYYY_MM_DD_EN("yyyy/MM/dd"), MM_DD_HH_MM_EN("MM/dd HH:mm"), MM_DD_HH_MM_SS_EN("MM/dd HH:mm:ss"), YYYY_MM_DD_HH_MM_EN("yyyy/MM/dd HH:mm"), YYYY_MM_DD_HH_MM_SS_EN("yyyy/MM/dd HH:mm:ss"), MM_DD_CN("MMdd"), YYYY_MM_CN("yyyyMM"), YYYY_MM_DD_CN("yyyyMMdd"), MM_DD_HH_MM_CN("MMdd HH:mm"), MM_DD_HH_MM_SS_CN("MMdd HH:mm:ss"), YYYY_MM_DD_HH_MM_CN("yyyyMMdd HH:mm"), YYYY_MM_DD_HH_MM_SS_CN("yyyyMMdd HH:mm:ss"), HH_MM("HH:mm"), HH_MM_SS("HH:mm:ss"); private String value; DateStyle(String value) { this.value = value; } public String getValue() { return value; } } /** * 周枚举 */ enum Week { MONDAY("һ", "Monday", "Mon.", 1), TUESDAY("ڶ", "Tuesday", "Tues.", 2), WEDNESDAY("", "Wednesday", "Wed.", 3), THURSDAY("", "Thursday", "Thur.", 4), FRIDAY("", "Friday", "Fri.", 5), SATURDAY("", "Saturday", "Sat.", 6), SUNDAY("", "Sunday", "Sun.", 7); String name_cn; String name_en; String name_enShort; int number; Week(String name_cn, String name_en, String name_enShort, int number) { this.name_cn = name_cn; this.name_en = name_en; this.name_enShort = name_enShort; this.number = number; } public String getChineseName() { return name_cn; } public String getName() { return name_en; } public String getShortName() { return name_enShort; } public int getNumber() { return number; } } /** * 解析各种格式出生年月,获取日期 * @param birthdate * @return */ public static Date getDateByString(String birthdate) { Date date = null; try{ birthdate = birthdate.trim(); if(birthdate.length() > 8){ if(birthdate.contains("-")){ date = getDateFormat(YYYY_MM_DD).parse(birthdate); }else if(birthdate.contains(".")){ date = getDateFormat(DATE_FORMAT_1).parse(birthdate); }else if(birthdate.contains("/")){ date = getDateFormat(DATE_FORMAT_2).parse(birthdate); } }else{ if(birthdate.contains("-")){ date = getDateFormat(DATE_FORMAT_3).parse(birthdate); }else if(birthdate.contains(".")){ date = getDateFormat(DATE_FORMAT_4).parse(birthdate); }else if(birthdate.contains("/")){ date = getDateFormat(DATE_FORMAT_5).parse(birthdate); } } }catch (Exception e){ } return date; } /** * 获取两个日期相差天数 * @param date 时间戳 * @param otherDate 第二个时间戳 * @return int */ public static int getIntervalDays(String date, String otherDate) { return getIntervalDays(StringToDate(date), StringToDate(otherDate)); } /** * 获取两个日期相差天数 * @param date 时间 * @param otherDate 第二个时间 * @return int */ public static int getIntervalDays(Date date, Date otherDate) { date = DateUtils.StringToDate(DateUtils.getDate(date)); long time = Math.abs(date.getTime() - otherDate.getTime()); return (int)time/(24 * 60 * 60 * 1000); } /** * 获取当前时间 * @return Date */ public static Date getNowDate(){ return new Date(); } /** * 获取当前时间的月份 * @return String */ public static String getThisMonth(){ SimpleDateFormat format = getDateFormat(YYYY_MM_DD); Calendar c = Calendar.getInstance(); c.add(Calendar.MONTH, 0); c.set(Calendar.DAY_OF_MONTH,1);//Ϊ1,ǰڼΪµһ String thisMonth = format.format(c.getTime()); return thisMonth; } /** * 获取当前时间的下一月份 * @return String */ public static String getNextMonth(){ SimpleDateFormat format = getDateFormat(YYYY_MM_DD); Calendar cal_1=Calendar.getInstance(); cal_1.add(Calendar.MONTH, +1); cal_1.set(Calendar.DAY_OF_MONTH,1); String nextMonth = format.format(cal_1.getTime()); return nextMonth; } /** * 字符串时间戳转Date * @param date * @return Date */ public static Date StringToDate(String date) { DateStyle dateStyle = null; return StringToDate(date, dateStyle); } /** * Date转Int * @param date 时间 * @param dateType 时间类型(年、月、日、时、分、秒等) * @return int */ private static int getInteger(Date date, int dateType) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(dateType); } /** * 时间计算,返回字符串 * @param date 时间戳 * @param dateType 时间类型(年、月、日、时、分、秒等) * @param amount 偏移量 * @return String */ private static String addInteger(String date, int dateType, int amount) { String dateString = null; DateStyle dateStyle = getDateStyle(date); if (dateStyle != null) { Date myDate = StringToDate(date, dateStyle); myDate = addInteger(myDate, dateType, amount); dateString = DateToString(myDate, dateStyle); } return dateString; } /** * 时间计算,返回Date * @param date 时间戳 * @param dateType 时间类型(年、月、日、时、分、秒等) * @param amount 偏移量 * @return Date */ private static Date addInteger(Date date, int dateType, int amount) { Date myDate = null; if (date != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(dateType, amount); myDate = calendar.getTime(); } return myDate; } /** * 时间年份偏移计算 * @param date 时间戳 * @param yearAmount 偏移量 * @return String */ public static String addYear(String date, int yearAmount) { return addInteger(date, Calendar.YEAR, yearAmount); } /** * 时间年份偏移计算 * @param date 时间 * @param yearAmount 偏移量 * @return Date */ public static Date addYear(Date date, int yearAmount) { return addInteger(date, Calendar.YEAR, yearAmount); } /** * 时间月份偏移计算 * @param date 时间戳 * @param monthAmount 偏移量 * @return String */ public static String addMonth(String date, int monthAmount) { return addInteger(date, Calendar.MONTH, monthAmount); } /** * 时间月份偏移计算 * @param date 时间 * @param monthAmount 偏移量 * @return Date */ public static Date addMonth(Date date, int monthAmount) { return addInteger(date, Calendar.MONTH, monthAmount); } /** * 时间天数偏移计算 * @param date 时间戳 * @param dayAmount 偏移量 * @return String */ public static String addDay(String date, int dayAmount) { return addInteger(date, Calendar.DATE, dayAmount); } /** * 时间天数偏移计算 * @param date 时间 * @param dayAmount 偏移量 * @return Date */ public static Date addDay(Date date, int dayAmount) { return addInteger(date, Calendar.DATE, dayAmount); } /** * 时间小时偏移计算 * @param date 时间戳 * @param hourAmount 偏移量 * @return String */ public static String addHour(String date, int hourAmount) { return addInteger(date, Calendar.HOUR_OF_DAY, hourAmount); } /** * 时间小时偏移计算 * @param date 时间 * @param hourAmount 偏移量 * @return Date */ public static Date addHour(Date date, int hourAmount) { return addInteger(date, Calendar.HOUR_OF_DAY, hourAmount); } /** * 时间分钟偏移计算 * @param date 时间戳 * @param minuteAmount 偏移量 * @return String */ public static String addMinute(String date, int minuteAmount) { return addInteger(date, Calendar.MINUTE, minuteAmount); } /** * 时间分钟偏移计算 * @param date 时间 * @param minuteAmount 偏移量 * @return Date */ public static Date addMinute(Date date, int minuteAmount) { return addInteger(date, Calendar.MINUTE, minuteAmount); } /** * 时间秒偏移计算 * @param date 时间戳 * @param secondAmount 偏移量 * @return String */ public static String addSecond(String date, int secondAmount) { return addInteger(date, Calendar.SECOND, secondAmount); } /** * 时间秒偏移计算 * @param date 时间 * @param secondAmount 偏移量 * @return Date */ public static Date addSecond(Date date, int secondAmount) { return addInteger(date, Calendar.SECOND, secondAmount); } /** * 获取时间的年份 * @param date 时间戳 * @return */ public static int getYear(String date) { return getYear(StringToDate(date)); } /** * 获取时间的年份 * @param date 时间 * @return */ public static int getYear(Date date) { return getInteger(date, Calendar.YEAR); } /** * 获取时间的月份 * @param date 时间戳 * @return */ public static int getMonth(String date) { return getMonth(StringToDate(date)); } /** * 获取时间的月份 * @param date 时间 * @return */ public static int getMonth(Date date) { return getInteger(date, Calendar.MONTH); } /** * 获取时间的天 * @param date 时间戳 * @return */ public static int getDay(String date) { return getDay(StringToDate(date)); } /** * 获取时间的天 * @param date 时间 * @return */ public static int getDay(Date date) { return getInteger(date, Calendar.DATE); } /** * 获取时间的小时 * @param date 时间戳 * @return */ public static int getHour(String date) { return getHour(StringToDate(date)); } /** * 获取时间的小时 * @param date 时间 * @return */ public static int getHour(Date date) { return getInteger(date, Calendar.HOUR_OF_DAY); } /** * 获取时间的分钟 * @param date 时间戳 * @return */ public static int getMinute(String date) { return getMinute(StringToDate(date)); } /** * 获取时间的分钟 * @param date 时间 * @return */ public static int getMinute(Date date) { return getInteger(date, Calendar.MINUTE); } /** * 获取时间的秒 * @param date 时间戳 * @return */ public static int getSecond(String date) { return getSecond(StringToDate(date)); } /** * 获取时间的秒 * @param date 时间 * @return */ public static int getSecond(Date date) { return getInteger(date, Calendar.SECOND); } /** * 获取日期 * @param date 时间戳 * @return */ public static String getDate(String date) { return StringToString(date, DateStyle.YYYY_MM_DD); } /** * 获取日期 * @param date 时间 * @return */ public static String getDate(Date date) { return DateToString(date, DateStyle.YYYY_MM_DD); } /** * 获取时分秒 * @param date 时间戳 * @return */ public static String getTime(String date) { return StringToString(date, DateStyle.HH_MM_SS); } /** * 获取时分秒 * @param date 时间 * @return */ public static String getTime(Date date) { return DateToString(date, DateStyle.HH_MM_SS); } /** * 获取周 * @param date 时间戳 * @return */ public static Week getWeek(String date) { Week week = null; DateStyle dateStyle = getDateStyle(date); if (dateStyle != null) { Date myDate = StringToDate(date, dateStyle); week = getWeek(myDate); } return week; } /** * 获取周 * @param date 时间 * @return */ public static Week getWeek(Date date) { Week week = null; Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int weekNumber = calendar.get(Calendar.DAY_OF_WEEK) - 1; switch (weekNumber) { case 0: week = Week.SUNDAY; break; case 1: week = Week.MONDAY; break; case 2: week = Week.TUESDAY; break; case 3: week = Week.WEDNESDAY; break; case 4: week = Week.THURSDAY; break; case 5: week = Week.FRIDAY; break; case 6: week = Week.SATURDAY; break; } return week; } /** * 判断字符串是否是时间戳 * @param date 时间戳 * @return boolean */ public static boolean isDate(String date) { boolean isDate = false; if (date != null) { if (StringToDate(date) != null) { isDate = true; } } return isDate; } /** * 获取字符串时间戳格式 * @param date 时间戳 * @return DateStyle */ public static DateStyle getDateStyle(String date) { DateStyle dateStyle = null; Map map = new HashMap(); List timestamps = new ArrayList(); for (DateStyle style : DateStyle.values()) { Date dateTmp = StringToDate(date, style.getValue()); if (dateTmp != null) { timestamps.add(dateTmp.getTime()); map.put(dateTmp.getTime(), style); } } dateStyle = map.get(getAccurateDate(timestamps).getTime()); return dateStyle; } /** * 获取SimpleDateFormat对象 * @param format 格式 * @return SimpleDateFormat * @throws RuntimeException */ private static SimpleDateFormat getDateFormat(String format) throws RuntimeException { return new SimpleDateFormat(format); } public static String dateToString2(Date date) { return new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS).format(date); } /** * 字符串转Date * @param date 时间戳 * @param format 格式 * @return Date */ public static Date StringToDate(String date, String format) { Date myDate = null; if (date != null) { try { myDate = getDateFormat(format).parse(date); } catch (Exception e) { } } return myDate; } /** * 字符串时间戳转Date * @param date 时间戳 * @param dateStyle 时间示例 * @return Date */ public static Date StringToDate(String date, DateStyle dateStyle) { Date myDate = null; if (dateStyle == null) { List timestamps = new ArrayList(); for (DateStyle style : DateStyle.values()) { Date dateTmp = StringToDate(date, style.getValue()); if (dateTmp != null) { timestamps.add(dateTmp.getTime()); } } myDate = getAccurateDate(timestamps); } else { myDate = StringToDate(date, dateStyle.getValue()); } return myDate; } /** * Date转字符串 * @param date 时间 * @param format 格式 * @return String */ public static String DateToString(Date date, String format) { String dateString = null; if (date != null) { try { dateString = getDateFormat(format).format(date); } catch (Exception e) { } } return dateString; } /** * Date转字符串 * @param date 时间 * @param dateStyle 时间示例 * @return String */ public static String DateToString(Date date, DateStyle dateStyle) { String dateString = null; if (dateStyle != null) { dateString = DateToString(date, dateStyle.getValue()); } return dateString; } /** * 字符串时间戳转字符串 * @param date 时间 * @param format 格式 * @return String */ public static String StringToString(String date, String format) { return StringToString(date, null, format); } /** * 字符串时间戳转字符串 * @param date 时间 * @param dateStyle 时间示例 * @return String */ public static String StringToString(String date, DateStyle dateStyle) { return StringToString(date, null, dateStyle); } /** * 字符串时间戳转字符串 * @param date 时间 * @param olddFormat 旧格式 * @param newFormat 新格式 * @return String */ public static String StringToString(String date, String olddFormat, String newFormat) { String dateString = null; if (olddFormat == null) { DateStyle style = getDateStyle(date); if (style != null) { Date myDate = StringToDate(date, style.getValue()); dateString = DateToString(myDate, newFormat); } } else { Date myDate = StringToDate(date, olddFormat); dateString = DateToString(myDate, newFormat); } return dateString; } /** * 字符串时间戳转字符串 * @param date 时间 * @param olddDteStyle 旧时间示例 * @param newDateStyle 新时间示例 * @return String */ public static String StringToString(String date, DateStyle olddDteStyle, DateStyle newDateStyle) { String dateString = null; if (olddDteStyle == null) { DateStyle style = getDateStyle(date); dateString = StringToString(date, style.getValue(), newDateStyle.getValue()); } else { dateString = StringToString(date, olddDteStyle.getValue(), newDateStyle.getValue()); } return dateString; } /** * 获取两个日期之间所有日期 * @param beginDatestr * @param endDatestr * @return * @throws Exception */ public static List genDateRange(String beginDatestr,String endDatestr) throws Exception{ Date beginDate = DateUtils.StringToDate(beginDatestr, DateUtils.YYYY_MM_DD); Date endDate = DateUtils.StringToDate(endDatestr, DateUtils.YYYY_MM_DD); if(beginDate.after(endDate)){ throw new Exception(""); } List datestrList = new ArrayList(); while(true){ String tmpbeginstr = DateUtils.DateToString(beginDate, DateUtils.YYYY_MM_DD); if(tmpbeginstr.equals(endDatestr)){ break; } beginDate = DateUtils.addDay(beginDate, 1); datestrList.add(tmpbeginstr); } return datestrList; } /** * 获取两个日期之间所有月份 * @param beginMonthstr * @param endMonthstr * @return * @throws Exception */ public static List genMonthRange(String beginMonthstr,String endMonthstr) throws Exception{ Date beginDate = DateUtils.StringToDate(beginMonthstr, "yyyy-MM"); Date endDate = DateUtils.StringToDate(endMonthstr, "yyyy-MM"); if(beginDate.after(endDate)){ throw new Exception(""); } List datestrList = new ArrayList(); while(true){ String tmpbeginstr = DateUtils.DateToString(beginDate, "yyyy-MM"); if(tmpbeginstr.equals(endMonthstr)){ break; } beginDate = DateUtils.addMonth(beginDate, 1); datestrList.add(tmpbeginstr); } return datestrList; } /** * 获取一个日期往前/后推几个月的所有月份(包括自己) * @param beginMonth 日期 * @param addMonth 推几个月 * @return * @throws Exception */ public static List genMonthRange(Date beginMonth, int addMonth) throws Exception{ // 转换为yyyy-MM格式 String beginMonthStr = DateUtils.DateToString(beginMonth, "yyyy-MM"); Date beginDate = DateUtils.StringToDate(beginMonthStr, "yyyy-MM"); // 计算月份集合 List dateStrList = new ArrayList(); dateStrList.add(beginMonthStr); if (addMonth != 0) { // 如果addMonth不为0,计算出endDate if (addMonth > 0) { for (int i = 1; i <= addMonth; i++) { Date nextDate = DateUtils.addMonth(beginDate, i); String nextMonthStr = DateUtils.DateToString(nextDate, "yyyy-MM"); dateStrList.add(nextMonthStr); } } if (addMonth < 0) { for (int i = -1; i >= addMonth; i--) { Date nextDate = DateUtils.addMonth(beginDate, i); String nextMonthStr = DateUtils.DateToString(nextDate, "yyyy-MM"); dateStrList.add(0, nextMonthStr); } } } return dateStrList; } /** * 获取精准时间Date * @param timestamps * @return */ private static Date getAccurateDate(List timestamps) { Date date = null; long timestamp = 0; Map map = new HashMap(); List absoluteValues = new ArrayList(); if (timestamps != null && timestamps.size() > 0) { if (timestamps.size() > 1) { for (int i = 0; i < timestamps.size(); i++) { for (int j = i + 1; j < timestamps.size(); j++) { long absoluteValue = Math.abs(timestamps.get(i) - timestamps.get(j)); absoluteValues.add(absoluteValue); long[] timestampTmp = { timestamps.get(i), timestamps.get(j) }; map.put(absoluteValue, timestampTmp); } } long minAbsoluteValue = -1; if (!absoluteValues.isEmpty()) { minAbsoluteValue = absoluteValues.get(0); } for (int i = 0; i < absoluteValues.size(); i++) { for (int j = i + 1; j < absoluteValues.size(); j++) { if (absoluteValues.get(i) > absoluteValues.get(j)) { minAbsoluteValue = absoluteValues.get(j); } else { minAbsoluteValue = absoluteValues.get(i); } } } if (minAbsoluteValue != -1) { long[] timestampsLastTmp = map.get(minAbsoluteValue); if (absoluteValues.size() > 1) { timestamp = Math.max(timestampsLastTmp[0], timestampsLastTmp[1]); } else if (absoluteValues.size() == 1) { long dateOne = timestampsLastTmp[0]; long dateTwo = timestampsLastTmp[1]; if ((Math.abs(dateOne - dateTwo)) < 100000000000L) { timestamp = Math.max(timestampsLastTmp[0], timestampsLastTmp[1]); } else { long now = new Date().getTime(); if (Math.abs(dateOne - now) <= Math.abs(dateTwo - now)) { timestamp = dateOne; } else { timestamp = dateTwo; } } } } } else { timestamp = timestamps.get(0); } } if (timestamp != 0) { date = new Date(timestamp); } return date; } public static String replaceNumber(String number){ String date = number.replace("1", "一").replace("2", "二").replace("3", "三").replace("4", "四"). replace("5", "五").replace("6", "六").replace("7", "七").replace("8", "八"). replace("9", "九").replace("0", "〇"); return date; } public static String getBirthday(String oldBirthday){ if (StringUtils.isNotEmpty(oldBirthday)) { String[] oldBirthdays = oldBirthday.split("-"); String birthday = oldBirthdays[0] + "年" + oldBirthdays[1] + "月" + oldBirthdays[2] + "日出生,"; return birthday; }else { return ""; } } /** * 获取固定格式时间,yyyy年MM月dd日上午 * * @param date * @return */ public static String getDocumentTime (Date date){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String newTime = sdf.format(new Date()); String[] newTimes = newTime.split("-"); String year = replaceNumber(newTimes[0]); String monthNumber = replaceNumber(newTimes[1]); char monthCharOne = monthNumber.charAt(0); char monthCharTwo = monthNumber.charAt(1); String month = ""; if ('〇' != monthCharOne){ if ('〇' != monthCharTwo) { if ('一' != monthCharOne) { month += monthCharOne + "十" + monthCharTwo; }else{ month += "十" + monthCharTwo; } }else{ if ('一' != monthCharOne) { month += monthCharOne + "十"; }else{ month += "十"; } } }else{ month += monthCharTwo; } String dayNumber = replaceNumber(newTimes[2]); char dayCharOne = dayNumber.charAt(0); char dayCharTwo = dayNumber.charAt(1); String day = ""; if ('〇' != dayCharOne){ if ('〇' != dayCharTwo){ if ('一' != dayCharOne){ day += dayCharOne+"十"+dayCharTwo; }else { day += "十"+dayCharTwo; } }else{ if ('一' != dayCharOne){ day += dayCharOne+"十"; }else { day += "十"; } } }else{ day += dayCharTwo; } return year+"年"+month+"月"+day+"日"; } /** * 获取两个时间的小时差 * */ public static Integer getDifferHour(Date time1,Date time2){ if(ObjectUtils.isNotEmpty(time1) && ObjectUtils.isNotEmpty(time2)){ long housrs = 1000 * 60 * 60; long differ = time1.getTime() - time2.getTime(); long housr = differ / housrs; return Integer.valueOf(String.valueOf(housr)); } return 0; } } /** * -------------------_ooOoo_------------------- * ------------------o8888888o------------------ * ------------------88" . "88------------------ * ------------------(| -_- |)------------------ * ------------------O\ = /O------------------ * ---------------____/`---'\____--------------- * -------------.' \\| |// `.------------- * ------------/ \\||| : |||// \------------ * -----------/ _||||| -:- |||||- \----------- * -----------| | \\\ - /// | |----------- * -----------| \_| ''\---/'' | |----------- * -----------\ .-\__ `-` ___/-. /----------- * ---------___`. .' /--.--\ `. . __---------- * ------."" '< `.___\_<|>_/___.' >'"".------- * -----| | : `- \`.;`\ _ /`;.`/ - ` : | |----- * -----\ \ `-. \_ __\ /__ _/ .-` / /----- * ======`-.____`-.___\_____/___.-`____.-'====== * -------------------`=---=' * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * ---------佛祖保佑---hugeinfo---永无BUG---------- */