package cn.besteam.common.util; import cn.besteam.common.constant.ErrorCode; import cn.besteam.common.exception.BusinessException; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.commons.lang.time.DateUtils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * 时间工具类 * * @author jacob */ public class DateUtil { public static final String YYYY_MM_DD = "yyyy-MM-dd"; public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss"; public static final String FULL_TIME = "yyyyMMddHHmmss"; public static final String TIME = "HH:mm"; public static final String MONTH_TIME = "MM-dd HH:mm"; public static final String SCHEDULE_TIME = "yyyy.MM.dd HH:mm"; public static final String SCHEDULE_TIME_SMS = "yyyy年MM月dd日 HH时mm分"; public static final String yyyy_MM = "yyyy-MM"; public static final String yyyy = "yyyy"; /** * 计算两个日期之间的天数 * @param startDate 开始日期 * @param endDate 结束日期 * @return 天数 */ public static int getDaysBetweenDates(Date startDate, Date endDate) { if (startDate == null || endDate == null) { return 0; } long diffInMillies = endDate.getTime() - startDate.getTime(); return (int) (diffInMillies / (24 * 60 * 60 * 1000)) + 1; } public static final String YYYYMMDD = "yyyyMMdd"; public static final String TODAY_MINUTE = "yyyy-MM-dd HH:mm"; /** * Calendar实例 */ private static Calendar calendar; private static Calendar getCalendarInstance() { if (calendar != null) { return calendar; } else { return Calendar.getInstance(); } } /** * 转成格式 yyyy-MM-dd HH:mm * * @param date * @return */ public static String scheduleTime(Date date) { if (date == null) { return null; } return DateFormatUtils.format(date, SCHEDULE_TIME); } public static Date getCurrentTime() { return new Date(); } /** * 转化格式 * * @param date * @return */ public static String formatTime(Date date, String format) { if (date == null) { return null; } return DateFormatUtils.format(date, format); } /** * 转成默认格式yyyy-MM-dd HH:mm:ss * * @param date * @return */ public static String format(Date date) { if (date == null) { return null; } return DateFormatUtils.format(date, DEFAULT_PATTERN); } /** * 转成格式 HH:mm * * @param date * @return */ public static String time(Date date) { if (date == null) { return null; } return DateFormatUtils.format(date, TIME); } /** * 转成格式 HH:mm * * @param date * @return */ public static String sms(Date date) { if (date == null) { return null; } return DateFormatUtils.format(date, SCHEDULE_TIME_SMS); } /** * 转成格式 MM-dd HH:mm * * @param date * @return */ public static String monAndTime(Date date) { if (date == null) { return null; } return DateFormatUtils.format(date, MONTH_TIME); } /** * 转成格式 yyyy-MM * * @param date * @return */ public static String month(Date date) { if (date == null) { return null; } return DateFormatUtils.format(date, yyyy_MM); } /** * 将Date类型的日期转换为参数定义的格式的字符串。 * * @param date * @param pattern * @return */ public static String format(Date date, String pattern) { if (date == null || pattern == null) { return null; } return DateFormatUtils.format(date, pattern); } public static Date getCurrDate(String format) { DateFormat df = new SimpleDateFormat(format); try { String currDateStr = df.format(new Date()); return df.parse(currDateStr); } catch (Exception e) { } return null; } public static Date getDate(String format, Object day) { DateFormat df = new SimpleDateFormat(format); try { Date date = df.parse(String.valueOf(day)); date = DateUtil.beginDate(date); return date; } catch (Exception e) { } return null; } /** * 封装开始时间 * * @param date * @return */ public static Date beginDate(Date date) { if (null == date) { return null; } String beginDate = new SimpleDateFormat(YYYY_MM_DD).format(date) + " 00:00:00"; try { return new SimpleDateFormat(DEFAULT_PATTERN).parse(beginDate); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 封装结束时间 * * @param date * @return */ public static Date endDate(Date date) { if (null == date) { return null; } String endDate = new SimpleDateFormat(YYYY_MM_DD).format(date) + " 23:59:59"; try { return new SimpleDateFormat(DEFAULT_PATTERN).parse(endDate); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @param nowDate * @param day 负数表示减 * @return */ public static Date addDateByDay(Date nowDate, int day) { Calendar calendar = getCalendarInstance(); calendar.setTime(nowDate); calendar.add(Calendar.DATE, day); return calendar.getTime(); } /** * @param sdate * @param day * @param format * @return */ public static String addDateByStringDay(String sdate, int day, String format, String toFormat) { Date date = DateUtil.getDate(format, sdate); date = addDateByDay(date, day); String stringDate = DateUtil.format(date, toFormat); return stringDate; } /** * @param nowDate * @param hour 负数表示减 * @return */ public static Date addDateByHour(Date nowDate, int hour) { Calendar calendar = getCalendarInstance(); calendar.setTime(nowDate); calendar.add(Calendar.HOUR_OF_DAY, hour); return calendar.getTime(); } /** * @param nowDate * @param year 增加年份 负数表示减 * @return */ public static Date addDateByYear(Date nowDate, int year) { Calendar calendar = getCalendarInstance(); calendar.setTime(nowDate); calendar.add(Calendar.YEAR, year); return calendar.getTime(); } /** * String转Date * * @param strDate * @return */ public static Date stringToDateTime(String strDate, String pattern) { if (null == strDate) { return null; } SimpleDateFormat sdf = new SimpleDateFormat(pattern); try { return sdf.parse(strDate); } catch (Exception e) { throw new BusinessException(ErrorCode.ERR_500, "请输入正确的格式"); } } public static Date stringToDateTime(String strDate) { return stringToDateTime(strDate, DEFAULT_PATTERN); } public static Date stringToDate(String strDate) { return stringToDateTime(strDate, YYYY_MM_DD); } public static Date stringToTime(String strDate) { return stringToDateTime(strDate, TIME); } /** * 上周一统计开始时间00 * * @return */ public static Date lastWednesday() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -7); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); return beginDate(cal.getTime()); } /** * 上周日统计结束时间 12 * * @return */ public static Date lastSunday() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); String endDate = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()) + " 12:00:00"; try { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDate); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 根据日期取得星期几 * * @param date * @return * @Date 2016年12月14日, 下午11:38:01 * @author YYF */ public static String getWeek(Date date) { String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; Calendar cal = Calendar.getInstance(); cal.setTime(date); int weekIndex = cal.get(Calendar.DAY_OF_WEEK) - 1; if (weekIndex < 0) { weekIndex = 0; } return weeks[weekIndex]; } /** * 比较两个日期的大小 * * @param date1 * @param date2 * @return 1. date1>date2 0.date1=date2 -1.date1 time2) { ret = 1; } else if (time1 == time2) { ret = 0; } else { ret = -1; } return ret; } /** * 计算当前时间和指定时间之间相差的小时 * * @param smdate 指定的时间 * @throws ParseException */ public static int hourBetween(String smdate) { Date start = new Date(); Date end = stringToDateTime(smdate); Calendar cal = Calendar.getInstance(); cal.setTime(start); long time1 = cal.getTimeInMillis(); cal.setTime(end); long time2 = cal.getTimeInMillis(); long betweenDays = (time2 - time1) / (1000 * 3600); return Integer.parseInt(String.valueOf(betweenDays)); } // public static void main(String[] args) { //// System.out.println(hourBetween("2017-01-13 00:00:00")); // System.out.println(format(addDateByYear(new Date(), -7))); // } /** * 比较两个日期相差的天数 * * @param createTime * @param today * @return * @author LHB */ public static Object differentDays(Date createTime, Date today) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(createTime); Calendar cal2 = Calendar.getInstance(); cal2.setTime(today); int createDay = cal1.get(Calendar.DAY_OF_MONTH); int todayDay = cal2.get(Calendar.DAY_OF_MONTH); int createMonth = cal1.get(Calendar.MONTH); int todayMonth = cal2.get(Calendar.MONTH); int createYear = cal1.get(Calendar.YEAR); int todayYear = cal2.get(Calendar.YEAR); // 同一年 if (createYear == todayYear) { if (createMonth == todayMonth) { if (todayDay - createDay == 0) { return "今天" + " " + time(createTime); } if (todayDay - createDay == 1) { return "昨天" + " " + time(createTime); } return monAndTime(createTime); } else { return monAndTime(createTime); } } else // 不同年 { return format(createTime); } } /** * 比较两个日期相差的数 * * @param createTime * @param today * @param type:1年,2月,3日 * @return * @author LHB */ public static Integer differentNumber(Date createTime, Date today,Integer type) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(createTime); Calendar cal2 = Calendar.getInstance(); cal2.setTime(today); int createStart=0; int createEnd=0; if(type==1){//年 createStart = cal1.get(Calendar.YEAR); createEnd = cal2.get(Calendar.YEAR); }else if(type==2){//月 createStart = cal1.get(Calendar.MONTH); createEnd = cal2.get(Calendar.MONTH); }else{ createStart = cal1.get(Calendar.DATE); createEnd = cal2.get(Calendar.DATE); } return createEnd - createStart; } /** * 比较是否同年同月 * * @param createTime * @param today * @return * @author LHB */ public static String differentMonths(Date createTime, Date today) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(createTime); Calendar cal2 = Calendar.getInstance(); cal2.setTime(today); int createMonth = cal1.get(Calendar.MONTH); int todayMonth = cal2.get(Calendar.MONTH); int createYear = cal1.get(Calendar.YEAR); int todayYear = cal2.get(Calendar.YEAR); // 同一年 if (createYear == todayYear) { if (createMonth == todayMonth) { return "SAME_MONTH"; } } else // 不同年 { return "DIFFERENT_YEAR"; } return null; } /** * 校验是否同年同月 * * @param updateTime * @param today * @return * @author LHB */ public static String differentMonth(Date updateTime, Date today) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(updateTime); Calendar cal2 = Calendar.getInstance(); cal2.setTime(today); int createMonth = cal1.get(Calendar.MONTH); int todayMonth = cal2.get(Calendar.MONTH); int createYear = cal1.get(Calendar.YEAR); int todayYear = cal2.get(Calendar.YEAR); // 同一年 if (createYear == todayYear) { if (createMonth == todayMonth) { return "same"; } else { return "different"; } } else // 不同年 { return "different"; } } /** * 返回前六个月 * * @param date * @return */ public static List getMonth(Date date) { Calendar calendar = Calendar.getInstance(); List dates = new ArrayList<>(); for (int i = 0; i < 6; i++) { Date month = calendar.getTime(); dates.add(month); calendar.add(Calendar.MONTH, -1); } return dates; } /** * 返回上一个月 * * @param date * @return */ public static Date lastMonth(Date date) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTime(date); calendar.add(Calendar.MONTH, -1); Date month = calendar.getTime(); return month; } /** * 获取上个月第一天 * * @return */ public static Date lastMonthFirstDay() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, -1); calendar.set(Calendar.DAY_OF_MONTH, 1); return calendar.getTime(); } /** * 获取上个月最后一天 * * @return */ public static Date lastMonthLastDay() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, 0); return calendar.getTime(); } /** * 获取年份第一天 00:00:00 * * @param year * @return */ public static Date getYearFirst(int year) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); return DateUtil.beginDate(calendar.getTime()); } /** * 获取年份最后一天 23:59:59 * * @param year * @return */ public static Date getYearLast(int year) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.roll(Calendar.DAY_OF_YEAR, -1); return DateUtil.endDate(calendar.getTime()); } /** * 获取月份第一天 00:00:00 * * @param date * @return */ public static Date getMonthFirstDay(Date date) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH, 1); return beginDate(calendar.getTime()); } /** * 获取月份第一天 00:00:00 * * @param date * @return */ public static Date getMonthLastDay(Date date) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTime(date); calendar.add(Calendar.MONTH, 1); calendar.set(Calendar.DAY_OF_MONTH, 0); return endDate(calendar.getTime()); } /** * 获取今天的日期 yyyyMMdd * * @return */ public static String getToday() { Date today = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YYYYMMDD); return simpleDateFormat.format(today); } /** * 把yyyy-MM-dd HH:mm 格式转化为今日的Date * * @param str * @return */ public static Date parseTime(String str, Date now) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(TODAY_MINUTE); str = parseDate(now) + " " + str; Date date = null; try { date = simpleDateFormat.parse(str); } catch (ParseException e) { return null; } return date; } /** * 判断now是否在date1和date2之间 * * @param now 现在 * @param date1 小的时间 * @param date2 大的时间 * @return */ public static boolean isMiddle(Date now, Date date1, Date date2) { if (date1.getTime() > date2.getTime()) { Date date = date1; date1 = date2; date2 = date; } return now.getTime() > date1.getTime() && now.getTime() < date2.getTime(); } /** * 判断是否是上班打卡时间 * * @param now * @param dateStr HH:mm * @param validTime 分钟 * @return */ public static boolean isGoToWork(Date now, String dateStr, long validTime) { validTime *= 1000 * 60 * validTime; dateStr = parseDate(now) + " " + dateStr; Date goToWorkTime2 = parseTime(dateStr, now); long time = goToWorkTime2.getTime(); Date goToWorkTime1 = new Date(time - validTime); return isMiddle(now, goToWorkTime1, goToWorkTime2); } /** * 判断是否是下班打卡时间 * * @param now * @param dateStr HH:mm * @param validTime * @return */ public static boolean isComeOffWork(Date now, String dateStr, long validTime) { validTime *= 1000 * 60 * validTime; dateStr = parseDate(now) + " " + dateStr; Date comeOffWork1 = parseTime(dateStr, now); long time = comeOffWork1.getTime(); Date comeOffWork2 = new Date(time + validTime); return isMiddle(now, comeOffWork1, comeOffWork2); } /** * 把date 转化为 yyyy-MM-dd * * @param date * @return */ public static String parseDate(Date date) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YYYY_MM_DD); return simpleDateFormat.format(date); } /** * 把yyyy-MM-dd 转化为date * * @param str * @return */ public static Date stringYearToDay(String str) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YYYY_MM_DD); try { return simpleDateFormat.parse(str); } catch (ParseException e) { throw new BusinessException(ErrorCode.ERR_500, "格式错误,正确格式为:" + YYYY_MM_DD); } } /**最近7日的日期列表,包含今日*/ public static List getSevenDate() { List dateList = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); for (int i = 6; i >= 0; i--) { Date date = DateUtils.addDays(new Date(), -i); String formatDate = sdf.format(date); dateList.add(formatDate); } return dateList; } /**获取两个时间节点之间的月份列表**/ public static List getMonthBetween(String minDate, String maxDate){ ArrayList result = new ArrayList(); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月 Calendar min = Calendar.getInstance(); Calendar max = Calendar.getInstance(); min.setTime(sdf.parse(minDate)); min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1); max.setTime(sdf.parse(maxDate)); max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2); Calendar curr = min; while (curr.before(max)) { result.add(sdf.format(curr.getTime())); curr.add(Calendar.MONTH, 1); } } catch (ParseException e) { e.printStackTrace(); } return result; } /** * 获取两个时间节点之间的月份列表 * @param minDate * @param maxDate * @param type 1 = 日 2 = 月 3 = 季 4 = 年 * @return */ public static List getMonthBetween(String minDate, String maxDate,Integer type){ ArrayList result = new ArrayList(); try { if(type==4){//年 SimpleDateFormat sdf = new SimpleDateFormat("yyyy");//格式化为年 Calendar min = Calendar.getInstance(); Calendar max = Calendar.getInstance(); min.setTime(sdf.parse(minDate)); max.setTime(sdf.parse(maxDate)); Calendar curr = min; max.add(Calendar.YEAR, 1); while (curr.before(max)) { result.add(sdf.format(curr.getTime())); curr.add(Calendar.YEAR, 1); } }else if(type == 2 || type == 3){//月 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月 Calendar min = Calendar.getInstance(); Calendar max = Calendar.getInstance(); min.setTime(sdf.parse(minDate)); max.setTime(sdf.parse(maxDate)); Calendar curr = min; max.add(Calendar.MONTH, 1); while (curr.before(max)) { result.add(sdf.format(curr.getTime())); curr.add(Calendar.MONTH, 1); } }else {//日 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//格式化为年月日 Calendar min = Calendar.getInstance(); Calendar max = Calendar.getInstance(); min.setTime(sdf.parse(minDate)); max.setTime(sdf.parse(maxDate)); Calendar curr = min; max.add(Calendar.DATE, 1); while (curr.before(max)) { result.add(sdf.format(curr.getTime())); curr.add(Calendar.DATE, 1); } } } catch (ParseException e) { e.printStackTrace(); } return result; } public static void main(String[] args) { // System.out.println(hourBetween("2017-01-13 00:00:00")); System.out.println(getMonthBetween("2020-01-01 00:00:00","2020-01-30 00:00:00",3)); } }