123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711 |
- package com.zhongzheng.common.utils;
- import cn.hutool.core.lang.Validator;
- import org.apache.commons.lang3.RandomStringUtils;
- import org.apache.commons.lang3.time.DateFormatUtils;
- import java.lang.management.ManagementFactory;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.time.*;
- import java.time.format.DateTimeFormatter;
- import java.util.*;
- /**
- * 时间工具类
- *
- * @author zhongzheng
- */
- public class DateUtils extends org.apache.commons.lang3.time.DateUtils
- {
- public static String YYYY = "yyyy";
- public static String YYYY_MM = "yyyy-MM";
- public static String YYYY_MM_DD = "yyyy-MM-dd";
- public static String YYYYMMDD = "yyyyMMdd";
- public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
- public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
- private static String[] parsePatterns = {
- "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
- "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
- "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
- /**
- * 获取当前Date型日期
- *
- * @return Date() 当前日期
- */
- public static Date getNowDate()
- {
- return new Date();
- }
- /**
- * 获取当前日期, 默认格式为yyyy-MM-dd
- *
- * @return String
- */
- public static String getDate()
- {
- return dateTimeNow(YYYY_MM_DD);
- }
- public static final String getTime()
- {
- return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
- }
- public static final String dateTimeNow()
- {
- return dateTimeNow(YYYYMMDDHHMMSS);
- }
- public static final String dateTimeNow(final String format)
- {
- return parseDateToStr(format, new Date());
- }
- public static final String dateTime(final Date date)
- {
- return parseDateToStr(YYYY_MM_DD, date);
- }
- public static final String parseDateToStr(final String format, final Date date)
- {
- return new SimpleDateFormat(format).format(date);
- }
- public static final Date dateTimeThrow(final String format, final String ts) throws ParseException {
- return new SimpleDateFormat(format).parse(ts);
- }
- public static final Date dateTime(final String format, final String ts)
- {
- try
- {
- return new SimpleDateFormat(format).parse(ts);
- }
- catch (ParseException e)
- {
- throw new RuntimeException(e);
- }
- }
- public static final Long dateTimeSec(final String format, final String ts)
- {
- try
- {
- return (new SimpleDateFormat(format).parse(ts)).getTime()/1000;
- }
- catch (ParseException e)
- {
- throw new RuntimeException(e);
- }
- }
- public static String timestampToDateFormat(Long times){
- if(Validator.isEmpty(times)){
- return "";
- }
- long t = times.longValue();
- t = t * 1000;
- Date date = new Date(t);
- return DateFormatUtils.format(date, "yyyy/MM/dd");
- }
- public static Date timeToDate(Long times){
- long t = times.longValue();
- t = t * 1000;
- return new Date(t);
- }
- public static String timestampToDateFormatMonth(Long times){
- if(Validator.isEmpty(times)){
- return "";
- }
- long t = times.longValue();
- t = t * 1000;
- Date date = new Date(t);
- return DateFormatUtils.format(date, "MM月dd号");
- }
- public static String timestampToDateFormatMonthTwo(Long times){
- if(Validator.isEmpty(times)){
- return "";
- }
- long t = times.longValue();
- t = t * 1000;
- Date date = new Date(t);
- return DateFormatUtils.format(date, "MM.dd");
- }
- public static String timestampToDateFormat(Long times,String patternStr){
- if(Validator.isEmpty(times)){
- return "";
- }
- long t = times.longValue();
- t = t * 1000;
- Date date = new Date(t);
- return DateFormatUtils.format(date, patternStr);
- }
- /**
- * 将秒转为时分秒格式【01:01:01】
- * @param second 需要转化的秒数
- * @return
- */
- public static String secondConvertHourMinSecond(Long second) {
- String str = "";
- if (second == null || second < 0) {
- return str;
- }
- // 得到小时
- long h = second / 3600;
- str = h > 0 ? ((h < 10 ? ("0" + h) : h) + "时") : "";
- // 得到分钟
- long m = (second % 3600) / 60;
- str += m > 0? (m < 10 ? ("0" + m) : m) + "分":"";
- //得到剩余秒
- long s = second % 60;
- str += s > 0?(s < 10 ? ("0" + s) : s)+"秒":"";
- return str;
- }
- public static String timestampToDate(Long times){
- if(Validator.isEmpty(times)){
- return "";
- }
- long t = times.longValue();
- t = t * 1000;
- Date date = new Date(t);
- return dateTime(date);
- }
- /**
- * 日期路径 即年/月/日 如2018/08/08
- */
- public static final String datePath()
- {
- Date now = new Date();
- return DateFormatUtils.format(now, "yyyy/MM/dd");
- }
- /**
- * 日期路径 即年/月/日 如20180808
- */
- public static final String dateTime()
- {
- Date now = new Date();
- return DateFormatUtils.format(now, "yyyyMMdd");
- }
- /**
- * 日期型字符串转化为日期 格式
- */
- public static Date parseDate(Object str)
- {
- if (str == null)
- {
- return null;
- }
- try
- {
- return parseDate(str.toString(), parsePatterns);
- }
- catch (ParseException e)
- {
- return null;
- }
- }
- /**
- * 获取服务器启动时间
- */
- public static Date getServerStartDate()
- {
- long time = ManagementFactory.getRuntimeMXBean().getStartTime();
- return new Date(time);
- }
- /**
- * 计算两个时间差
- */
- public static String getDatePoor(Date endDate, Date nowDate)
- {
- long nd = 1000 * 24 * 60 * 60;
- long nh = 1000 * 60 * 60;
- long nm = 1000 * 60;
- // long ns = 1000;
- // 获得两个时间的毫秒时间差异
- long diff = endDate.getTime() - nowDate.getTime();
- // 计算差多少天
- long day = diff / nd;
- // 计算差多少小时
- long hour = diff % nd / nh;
- // 计算差多少分钟
- long min = diff % nd % nh / nm;
- // 计算差多少秒//输出结果
- // long sec = diff % nd % nh % nm / ns;
- return day + "天" + hour + "小时" + min + "分钟";
- }
- public static Long getNowTime()
- {
- return System.currentTimeMillis()/1000;
- }
- /**
- * 获取今天凌晨时间戳
- */
- public static Long getTodayZeroTime()
- {
- Calendar cal = Calendar.getInstance();
- cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
- return cal.getTimeInMillis() / 1000; //今天凌晨
- }
- /**
- * 获取指定时间的凌晨时间戳
- */
- public static Long getScheduleTimeStrZeroTime(String timeStr,String patternStr)
- {
- Long time = dateTimeSec(patternStr,timeStr);
- Calendar cal = Calendar.getInstance();
- cal.setTime(timeToDate(time));
- cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
- return cal.getTimeInMillis() / 1000; //今天凌晨
- }
- /**
- * 获取指定时间的凌晨时间戳
- */
- public static Long getScheduleTimeZeroTime(Long scheduleTime)
- {
- Calendar cal = Calendar.getInstance();
- cal.setTime(timeToDate(scheduleTime));
- cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
- return cal.getTimeInMillis() / 1000; //今天凌晨
- }
- public static String formatDate(Date time,String str)
- {
- SimpleDateFormat sdf = new SimpleDateFormat(str);
- return sdf.format(time);
- }
- /**
- * 获取明天凌晨时间戳
- */
- public static Long getTomorrowZeroTime()
- {
- Calendar cal = Calendar.getInstance();
- cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
- Calendar cal1 = Calendar.getInstance();
- cal1.setTime(cal.getTime());
- cal1.add(Calendar.DAY_OF_MONTH , +1);
- return cal1.getTimeInMillis() / 1000; //明天凌晨
- }
- /**
- * 获取当月第一天的凌晨时间戳
- */
- public static Long getToMonthZeroTime()
- {
- Calendar cal = Calendar.getInstance();
- cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 1, 0, 0, 0);
- return cal.getTime().getTime()/1000;
- }
- /**
- * 获取本年第一天的凌晨时间戳
- */
- public static Long getToYearZeroTime()
- {
- Calendar calendar = Calendar.getInstance();
- // 设置当前时间为年初的第一天
- calendar.set(Calendar.DAY_OF_YEAR, 1);
- Date startOfCurrentYear = calendar.getTime();
- return startOfCurrentYear.getTime()/1000;
- }
- /**
- * 根据当前日期获得所在周的日期区间(周一和周日日期)
- */
- public static Map<String, Long> getTimeInterval(Date date){
- Map<String, Long> map = new HashMap<>();
- Calendar cal = Calendar.getInstance();
- cal.setTime(date);
- // 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
- int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
- if(1 == dayWeek){
- cal.add(Calendar.DAY_OF_MONTH,-1);
- }
- // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
- cal.setFirstDayOfWeek(Calendar.MONDAY);
- // 获得当前日期是一个星期的第几天
- int day = cal.get(Calendar.DAY_OF_WEEK);
- // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
- cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
- Long imptimeBegin = cal.getTime().getTime();
- cal.add(Calendar.DATE,6);
- Long imptimeEnd = cal.getTime().getTime();
- map.put("start", imptimeBegin/1000);
- map.put("end", imptimeEnd/1000);
- return map;
- }
- /**
- * 根据当前日期获得上周的日期区间(上周周一和周日日期)
- */
- public static Map<String, Long> getLastTimeInterval(Date date){
- Map<String, Long> map = new HashMap<>();
- Calendar calendar1 = Calendar.getInstance();
- Calendar calendar2 = Calendar.getInstance();
- calendar1.setTime(date);
- calendar2.setTime(date);
- int dayOfWeek = calendar1.get(Calendar.DAY_OF_WEEK) - 1;
- if(dayOfWeek <= 0){
- dayOfWeek = 7;
- }
- int offset1 = 1 - dayOfWeek;
- int offset2 = 7 - dayOfWeek;
- calendar1.add(Calendar.DATE, offset1 - 7);
- calendar2.add(Calendar.DATE, offset2 - 7);
- // last Monday
- Long lastBeginDate = calendar1.getTime().getTime();
- // last Sunday
- Long lastEndDate = calendar2.getTime().getTime();
- map.put("laststart", lastBeginDate/1000);
- map.put("lastend", lastEndDate/1000);
- return map;
- }
- /**
- * 获取日期格式订单号
- * @return
- */
- public static String getDateOrderSn()
- {
- DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
- String localDate = (LocalDateTime.now().format(ofPattern)).substring(2);
- //随机数
- String randomNumeric = RandomStringUtils.randomNumeric(8);
- return localDate+randomNumeric;
- }
- public static String getDateInputOrderSn()
- {
- return "LD"+getDateOrderSn();
- }
- public static String getPayOrderSn()
- {
- return "P"+getDateOrderSn();
- }
- public static String getInvoiceOrderSn()
- {
- DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
- String localDate = (LocalDateTime.now().format(ofPattern)).substring(2);
- //随机数
- String randomNumeric = RandomStringUtils.randomNumeric(4);
- return "IN"+localDate+randomNumeric;
- }
- public static String getTagOrderSn(String tag)
- {
- return tag+getDateOrderSn();
- }
- public static String secToTime(int time) {
- String timeStr = null;
- int hour = 0;
- int minute = 0;
- int second = 0;
- if (time <= 0)
- return "00:00";
- else {
- minute = time / 60;
- if (minute < 60) {
- second = time % 60;
- timeStr = "00:"+unitFormat(minute) + ":" + unitFormat(second);
- } else {
- hour = minute / 60;
- if (hour > 99){
- return "99:59:59";
- }
- minute = minute % 60;
- second = time - hour * 3600 - minute * 60;
- timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
- }
- }
- return timeStr;
- }
- public static String unitFormat(int i) {
- String retStr = null;
- if (i >= 0 && i < 10)
- retStr = "0" + Integer.toString(i);
- else
- retStr = "" + i;
- return retStr;
- }
- public static Integer durationFormat(String duration) {
- int index1=duration.indexOf(":");
- int index2=duration.indexOf(":",index1+1);
- int hh=Integer.parseInt(duration.substring(0,index1));
- int mi=Integer.parseInt(duration.substring(index1+1,index2));
- int ss=Integer.parseInt(duration.substring(index2+1));
- return hh*60*60+mi*60+ss;
- }
- public static Integer dayBetween(Long s1,Long s2) {
- String date1str = timestampToDateFormat(s1);
- String date2str = timestampToDateFormat(s2);
- int count = 0;
- if("".equals(date1str) || date1str == null || "".equals(date2str) || date2str == null) {
- return count;
- }
- SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
- try {
- Date date1 = format.parse(date1str);
- Date date2 = format.parse(date2str);
- count = ((int) ((date1.getTime() - date2.getTime()) / (1000*3600*24)));
- return count;
- }catch (Exception e){
- return null;
- }
- }
- public static Integer getTodayWeek(){
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(new Date());
- int weekIdx = calendar.get(Calendar.DAY_OF_WEEK) - 1;
- switch (weekIdx) {
- case 1:
- return 1;
- case 2:
- return 2;
- case 3:
- return 3;
- case 4:
- return 4;
- case 5:
- return 5;
- case 6:
- return 6;
- default:
- return 7;
- }
- }
- public static LocalDate[] getDateArray() {
- // 创建一个长度为30的数组
- LocalDate[] dates = new LocalDate[30];
- // 获取今天的日期
- LocalDate today = LocalDate.now();
- // 用循环给数组赋值
- for (int i = 0; i < dates.length; i++) {
- // 用today.plusDays(i)得到第i天的日期
- dates[i] = today.plusDays(i);
- }
- // 返回数组
- return dates;
- }
- static List<String> holiday =new ArrayList<>();
- static List<String> extraWorkDay =new ArrayList<>();
- public static Boolean isWorkingDay(long time) {
- LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneOffset.of("+8"));
- String formatTime = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
- initHoliday();
- initExtraWorkDay();
- //是否加班日
- if(extraWorkDay.contains(formatTime)){
- return true;
- }
- //是否节假日
- if(holiday.contains(formatTime)){
- return false;
- }
- //如果是1-5表示周一到周五 是工作日
- DayOfWeek week = dateTime.getDayOfWeek();
- if(week==DayOfWeek.SATURDAY||week==DayOfWeek.SUNDAY){
- return false;
- }
- return true;
- }
- /**
- * 初始化节假日
- */
- public static void initHoliday(){
- holiday.add("2023-06-22");
- holiday.add("2023-06-23");
- holiday.add("2023-09-29");
- holiday.add("2023-09-30");
- holiday.add("2023-10-01");
- holiday.add("2023-10-02");
- holiday.add("2023-10-03");
- holiday.add("2023-10-04");
- holiday.add("2023-10-05");
- holiday.add("2023-10-06");
- }
- /**
- * 初始化额外加班日
- */
- public static void initExtraWorkDay(){
- extraWorkDay.add("2023-06-25");
- extraWorkDay.add("2023-10-07");
- extraWorkDay.add("2023-10-08");
- }
- public static Long getAppointTime(Long millisecond, Integer day) {
- for (Integer i = 0; i < day; i++) {
- Long dayAfter = getDayBefore(millisecond, 1);
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(timeToDate(dayAfter));
- int index = calendar.get(Calendar.DAY_OF_WEEK) - 1;
- String[] weeks = new String[]{"星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
- if (weeks[index].equals("星期六") || weeks[index].equals("星期天")) {
- day += 1;
- }
- //判断当前是否为工作日
- if (!isWorkingDay(dayAfter)) {
- day += 1;
- }
- millisecond = dayAfter;
- }
- return millisecond;
- }
- /**
- * 指定时间往前或往后推n天
- *
- * @param dateTime 指定时间
- * @param x 指定天数
- * @return
- */
- public static Long getDayBefore(Long dateTime, int x) {
- Calendar c = Calendar.getInstance();
- Date date = new Date(dateTime*1000);
- c.setTime(date);
- int day = c.get(Calendar.DATE);
- c.set(Calendar.DATE, day - x); //往前推几天
- //c.set(Calendar.DATE, day + x); 往后推几天
- return c.getTime().getTime()/1000;
- }
- /**
- * 指定时间往前或往后推n天
- *
- * @param dateTime 指定时间
- * @param x 指定天数
- * @return
- */
- public static Long getDayAfter(Long dateTime, int x) {
- Calendar c = Calendar.getInstance();
- Date date = new Date(dateTime*1000);
- c.setTime(date);
- int day = c.get(Calendar.DATE);
- // c.set(Calendar.DATE, day - x); //往前推几天
- c.set(Calendar.DATE, day + x); //往后推几天
- return c.getTime().getTime()/1000;
- }
- public static List<Long> getWeekData(Long dataTime){
- List<Long> week = new ArrayList();
- Calendar calendar = Calendar.getInstance();
- Long zeroTime = DateUtils.getScheduleTimeZeroTime(dataTime);
- calendar.setTime(timeToDate(zeroTime));
- // 如果是周日
- if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
- calendar.add(Calendar.DAY_OF_YEAR,-1);
- }
- // 获取当前日期是当周的第i天
- int i = calendar.get(Calendar.DAY_OF_WEEK) - 1;
- // 获取当前日期所在周的第一天
- calendar.add(Calendar.DATE , -i);
- for (int j = 0; j < 7; j++) {
- if(j >0){
- calendar.add(Calendar.DATE , 1);
- }
- Long time = calendar.getTime().getTime()/1000;
- if (j == 6){
- time = time + 86400L;
- }
- week.add(time);
- }
- return week;
- }
- public static Map<Long,Long> getWeekTime(Long startTime,Long endTime){
- Map<Long,Long> mapList = new LinkedHashMap<>();
- Long zeroTime = DateUtils.getScheduleTimeZeroTime(startTime);
- //一天的时间戳
- Long time = 86400L;
- for (Long i = zeroTime; i <= endTime; i = i+time) {
- List<Long> weekData = DateUtils.getWeekData(i);
- mapList.put(weekData.get(0),weekData.get(weekData.size()-1));
- }
- return mapList;
- }
- public static Map<Long,Long> getMonthTime(Long startTime,Long endTime){
- //一天的时间戳
- Long time = 86400L;
- Map<Long,Long> map = new LinkedHashMap<>();
- try{
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
- Date d1 = DateUtils.timeToDate(startTime);
- Date d2 = DateUtils.timeToDate(endTime);
- Calendar dd = Calendar.getInstance();//定义日期实例
- dd.setTime(d1);//设置日期起始时间
- while (dd.getTime().before(d2)) {//判断是否到结束日期
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
- String str = sdf.format(dd.getTime());
- Calendar c = Calendar.getInstance();
- c.setTime(format.parse(str));
- c.add(Calendar.MONTH, 0);
- c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
- Long start = c.getTime().getTime()/1000;
- dd.setTime(DateUtils.timeToDate(start));
- //获取当前月最后一天
- Calendar ca = Calendar.getInstance();
- ca.setTime(format.parse(str));
- ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
- Long end = ca.getTime().getTime()/1000 + time;
- map.put(start,end);
- dd.add(Calendar.MONTH, 1);//进行当前日期月份加1
- }
- }catch (Exception e){
- System.out.println("异常"+e.getMessage());
- }
- return map;
- }
- }
|