获取时间整形(Integer)类型工具类

依赖

    <!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.10.10</version>
        </dependency>

官网:https://www.joda.org/joda-time/quickstart.html 

package org.demo.util;


import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.Months;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class JodaTimeUtilAll {

    private static Logger logger = LoggerFactory.getLogger(JodaTimeUtilAll.class);

    /**
     * 当前的年月日 整形
     *
     * @return yyyyMMdd
     */
    public static String getNow() {
        return formatDateTime(new Date());
    }

    /**
     * 当前的年月日 整形
     *
     * @return yyyyMMdd
     */
    public static Integer getNowYmd() {
        DateTime dt = DateTime.now();
        return getYmd(dt);
    }

    /**
     * 当前的年月日+day 整形
     *
     * @return yyyyMMdd
     */
    public static Integer getNowYmd(int day) {
        DateTime dt = DateTime.now();
        dt = dt.plusDays(day);
        return getYmd(dt);
    }

    public static Integer getYmd(DateTime dt) {
        int ymd = dt.getYear() * 100000 + dt.getMonthOfYear() * 1000 + dt.getDayOfMonth() * 10;
        return Integer.valueOf(ymd / 10);
    }


    public static Integer getYmd(LocalDate ld) {
        int ymd = ld.getYear() * 100000 + ld.getMonthOfYear() * 1000 + ld.getDayOfMonth() * 10;
        return Integer.valueOf(ymd / 10);
    }

    /**
     * 当前的年月日+day 整形
     *
     * @return yyyyMMdd
     */
    public static Integer getDateYmd(Integer ymd, int day) {
        LocalDate ld = DateTimeFormat.forPattern("yyyyMMdd").parseLocalDate(String.valueOf(ymd));
        ld = ld.plusDays(day);
        return getYmd(ld);
    }

    /**
     * 当前的年月日+day 整形
     *
     * @return yyyyMMdd
     */
    public static Integer getDateYmdPlusMonth(Integer ymd, int month) {
        LocalDate ld = DateTimeFormat.forPattern("yyyyMMdd").parseLocalDate(String.valueOf(ymd));
        ld = ld.plusMonths(month);
        return getYmd(ld);
    }


    /**
     * 获取日期累加的天数的某个时间
     *
     * @param date 日期
     * @param day  间隔的天数
     * @param hms  开始时间、当前时间、结束时间
     * @return 日期
     */
    public static Date getDatePlusDays(Date date, int day, int hms) {
        DateTime dt = new DateTime(date.getTime());
        if (day != 0) {
            dt = dt.plusDays(day);
        }
        return (hms == 0 ? dt : (hms >= 1 ? dt.millisOfDay().withMaximumValue() :
                dt.millisOfDay().withMinimumValue())).toDate();
    }

    /**
     * 获取日期累加的天数的某个时间
     *
     * @param ymd 日期
     * @param day 间隔的天数
     * @param hms 开始时间、当前时间、结束时间
     * @return 日期
     */
    public static Date getYmdPlusDays(Integer ymd, int day, int hms) {
        DateTime dt = DateTimeFormat.forPattern("yyyyMMdd").parseDateTime(String.valueOf(ymd));
        if (day != 0) {
            dt = dt.plusDays(day);
        }
        return (hms == 0 ? dt : (hms >= 1 ? dt.millisOfDay().withMaximumValue() :
                dt.millisOfDay().withMinimumValue())).toDate();
    }

    /**
     * 获取指定日期的年月日 整形
     *
     * @param date 日期
     * @return yyyyMMdd
     */
    public static Integer getDateYmd(Date date) {
        DateTime dt = new DateTime(date.getTime());
        return getYmd(dt);
    }

    public static Integer getDateYmd(String dateStr, String pattern) {
        Date date = parseDate(dateStr, pattern);
        if (date == null) {
            return null;
        }
        DateTime dt = new DateTime(date.getTime());
        return getYmd(dt);
    }

    /**
     * 获取指定日期的之后的日期
     *
     * @param dateStr 指定日期
     * @param after   +天数
     * @return 返回格式:"yy-MM-dd"
     */
    public static String getDayAfterDateYmd(String dateStr, int after) {
        if (StringUtils.isEmpty(dateStr)) {
            return null;
        }
        try {
            Calendar c = Calendar.getInstance();
            Date date = new SimpleDateFormat("yy-MM-dd").parse(dateStr);
            c.setTime(date);
            int day = c.get(Calendar.DATE);
            c.set(Calendar.DATE, day + after);
            return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        } catch (ParseException e) {
            logger.error("获取指定日期之后的日期异常:{}", e);
            return null;
        }
    }

    /**
     * 批次号,追加当前的时分秒
     *
     * @param batchNo 批次号
     * @return 批次号+时分秒
     */
    public static String getBatchNoHms(String batchNo) {
        DateTime dt = DateTime.now();
        StringBuilder builder = new StringBuilder(batchNo);
        builder.append(String.format("%02d", dt.getHourOfDay()))
                .append(String.format("%02d", dt.getMinuteOfHour()))
                .append(String.format("%02d", dt.getSecondOfMinute()));
        return builder.toString();
    }

    public static String currentStackTrace() {
        StringBuilder sb = new StringBuilder();
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        for (StackTraceElement ste : stackTrace) {
            sb.append("\n\t");
            sb.append(ste.toString());
        }

        return sb.toString();
    }

    /**
     * 抽取Map中间某个key,不存在返回默认值
     *
     * @param key          key
     * @param objectMap    map值
     * @param defaultValue 默认值
     * @return value
     */
    public static String getMapValueForKey(String key, Map<String, Object> objectMap,
                                           String defaultValue) {
        Object obj = objectMap.get(key);
        return obj == null ? defaultValue : obj.toString();
    }

    /**
     * 计算耗时操作,单位ms
     */
    public static long countConsume(final long beginTime) {
        return (System.currentTimeMillis() - beginTime);
    }

    public static int asInt(String str, int defaultValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static long asLong(String str, long defaultValue) {
        try {
            return Long.parseLong(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static double asDouble(String str, double defaultValue) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * format date
     *
     * @param date 日期
     * @return 日期字符串
     */
    public static String formatDate(Date date) {
        return DateTimeFormat.forPattern("yyyy-MM-dd").print(date.getTime());
    }

    /**
     * format date
     *
     * @param date 日期
     * @return 日期字符串
     */
    public static String formatDateTime(Date date) {
        return DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").print(date.getTime());
    }

    /**
     * format date
     *
     * @param date 日期
     * @return 日期字符串
     */
    public static String formatDate(Date date, String pattern) {
        return DateTimeFormat.forPattern(pattern).print(date.getTime());
    }

    public static Date parseDate(int date) {
        return parseDate(String.valueOf(date), "yyyyMMdd");
    }

    public static Date parseDate(String date) {
        return parseDate(date, null);
    }

    public static Date parseDate(String date, String pattern) {
        DateTimeFormatter formatter = pattern == null ? DateTimeFormat.forPattern("yyyy-MM-dd") : DateTimeFormat.forPattern(pattern);
        try {
            LocalDate dateTime = formatter.parseLocalDate(date);
            return dateTime.toDate();
        } catch (Exception e) {
            return null;
        }
    }

    public static Date parseDateTime(String date) {
        return parseDateTime(date, null);
    }

    public static Date parseDateTime(String date, String pattern) {
        DateTimeFormatter formatter = pattern == null ? DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") : DateTimeFormat.forPattern(pattern);
        try {
            DateTime dateTime = formatter.parseDateTime(date);
            return dateTime.toDate();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 日期间隔多少天
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 日期1-日期2 所得天数
     */
    public static Integer dateDiff(Integer date1, Integer date2) {
        if (date1 == null || date2 == null) {
            return null;
        }
        return dateDiff(Integer.toString(date1), Integer.toString(date2));
    }

    /**
     * 日期间隔多少天
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 日期1-日期2 所得天数
     */
    public static Integer dateDiff(String date1, String date2) {
        if (date1 == null || date2 == null) {
            return null;
        }
        try {
            Calendar c = Calendar.getInstance();
            Date dateA = new SimpleDateFormat("yyyyMMdd").parse(date1);
            Date dateB = new SimpleDateFormat("yyyyMMdd").parse(date2);

            long diff = (dateA.getTime() - dateB.getTime()) / 1000L / 60 / 60 / 24;
            return new Long(diff).intValue();
        } catch (ParseException e) {
            logger.error("计算日期间隔天数异常:{}", e.getMessage(), e);
            return null;
        }
    }


    /**
     * 日期间隔多少天
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 日期1-日期2 所得天数
     */
    public static Integer dateDiff(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            return null;
        }
        try {
            long diff = (date2.getTime() - date1.getTime()) / 1000L / 60 / 60 / 24;
            return Math.abs(new Long(diff).intValue());
        } catch (Exception e) {
            logger.error("计算日期间隔天数异常:{}", e.getMessage(), e);
            return null;
        }
    }


    /**
     * 计算到期日和当前时间之间相差的天数,对应的延滞阶段和延滞天数
     *
     * @param dueToPayDateTime 到期日
     * @param nowDateTime      当前日期
     * @return 延滞阶段、延滞天数
     */
    public static List<Integer> calculationDelayLevelAndDays(LocalDate dueToPayDateTime, LocalDate nowDateTime) {
        long beginMillis = System.currentTimeMillis();

        List<Integer> resultList = Lists.newArrayListWithCapacity(2);
        // dueToPayDateTime >= nowDateTime,还未逾期跳过
        if (!dueToPayDateTime.isBefore(nowDateTime)) {
            resultList.add(Integer.valueOf(0));
            resultList.add(Integer.valueOf(0));
            return resultList;
        }

        // 计算到期日和当前时间的月份之差
        int months = Months.monthsBetween(dueToPayDateTime, nowDateTime).getMonths();
        LocalDate currentMonthDueToPayDateTime = dueToPayDateTime.plusMonths(months);
        // 对比到期日+月份之差后,是否大于当前时间
        int compareResult = currentMonthDueToPayDateTime.compareTo(nowDateTime);

        int days;
        if (compareResult > 0) {

            // currentMonthDueToPayDateTime > nowDateTime
            // 到期日+月份之差 > 当前时间,计算逾期天数,就是(到期日+月份之差)减一个月后对应的日期和当前日期相差的天数
            days = Days.daysBetween(currentMonthDueToPayDateTime.minusMonths(1), nowDateTime).getDays();
        } else if (compareResult < 0) {

            // currentMonthDueToPayDateTime < nowDateTime
            // 到期日+月份之差 < 当前时间,计算逾期天数,就是(到期日+月份之差)和当前日期相差的天数
            days = Days.daysBetween(currentMonthDueToPayDateTime, nowDateTime).getDays();
            months++;
        } else {

            // currentMonthDueToPayDateTime == nowDateTime
            // 到期日+月份之差 == 当前时间,计算逾期天数,就是(到期日+月份之差)减一个月后对应的日期的当月最对应的总天数
            days = currentMonthDueToPayDateTime.minusMonths(1).dayOfMonth().getMaximumValue();
        }
        resultList.add(months);
        resultList.add(days);

        logger.info("{}-{} M{}/{} times:{}ms.", dueToPayDateTime.toString("yyyyMMdd"),
                nowDateTime.toString("yyyyMMdd"), months, days, (System.currentTimeMillis() - beginMillis));
        return resultList;
    }

    /**
     * 获取下一次跟进时间
     * 当前时间小于等于12:00时,【下次跟进时间】设置为当日14:00;
     *  当前时间大于12:00小于等于18:00时,【下次跟进时间】设置为当日18:00;
     *  当前时间大于18:00小于等于20:00时,【下次跟进时间】设置为当日20:00;
     *  当前时间大于20:00时,【下次跟进时间】设置为次日09:00。
     *
     * @param nextFlowDatetime 下次跟进时间
     * @return 跟进时间
     */
    public static DateTime getNextFlowDatetime(Date nextFlowDatetime) {
        DateTime dateTime = new DateTime();
        if (null != nextFlowDatetime) {
            dateTime = dateTime.withMillis(nextFlowDatetime.getTime());
        }
        int hourOfDay = dateTime.getHourOfDay();
        if (hourOfDay < 12) {
            dateTime = dateTime.withHourOfDay(14);
        } else if (hourOfDay >= 12 && hourOfDay < 18) {
            dateTime = dateTime.withHourOfDay(18);
        } else if (hourOfDay >= 18 && hourOfDay < 20) {
            dateTime = dateTime.withHourOfDay(20);
        } else {
            dateTime = dateTime.plusDays(1);
            dateTime = dateTime.withHourOfDay(9);
        }

        dateTime = dateTime.withMinuteOfHour(0);
        dateTime = dateTime.withSecondOfMinute(0);
        return dateTime;
    }


    /**
     * 判断指定日期是否是周末
     *
     * @param day 指定日期
     * @return
     */
    public static boolean isWeekend(int day) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(DateUtil.parseDate(day));
        return cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY;
    }

    /**
     * 获取指定日期所在月份的天数
     *
     * @param day
     * @return
     */
    public static int daysOfMonth(int day) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(DateUtil.parseDate(day));
        return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param day 指定日期
     * @return 返回星期几
     */
    public static String getWeekOfDateXQ(int day) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(DateUtil.parseDate(day));
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }

    /**
     * 获取当前日期是周几<br>
     *
     * @param day 指定日期
     * @return 返回周几
     */
    public static String getWeekOfDateZ(int day) {
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(DateUtil.parseDate(day));
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }


    /**
     * 两个时间间隔多少个小时
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 间隔小时
     */
    public static Integer hourDiff(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            return null;
        }
        long diff = (date2.getTime() - date1.getTime()) / 1000L / 60 / 60;
        return Math.abs(new Long(diff).intValue());
    }

    /**
     * 间隔分钟数
     *
     * @param date1 时间1
     * @param date2 时间2
     * @return 时间1-时间2 所得分钟数
     */
    public static Integer minuteDiff(Date date1, Date date2) {
        Long minuteDiff = (date1.getTime() - date2.getTime()) / (1000 * 60);
        return minuteDiff.intValue();
    }

    /**
     * 间隔秒数
     *
     * @param date1 时间1
     * @param date2 时间2
     * @return 时间1-时间2 所得秒数
     */
    public static Integer secondDiff(Date date1, Date date2) {
        Long secondDiff = 0L;
        if (date1.getTime() > date2.getTime()) {
            secondDiff = (date1.getTime() - date2.getTime()) / 1000;
        } else {
            secondDiff = (date2.getTime() - date1.getTime()) / 1000;
        }
        return secondDiff.intValue();
    }

    /**
     * 输入时间+分钟
     *
     * @param date   时间
     * @param minute 分钟数
     * @return 时间+分钟数
     */
    public static Date getDatePlusMinute(Date date, int minute) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MINUTE, minute);
        return cal.getTime();
    }

    /**
     * 获取当前小时
     *
     * @author myx 15919918653 2019/5/29 20:37
     */
    public static int getNowHour() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        return calendar.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 时间 加N秒
     *
     * @param date
     * @param second
     * @return
     */
    public static Date addSecond(Date date, int second) {
        Calendar calendar = Calendar.getInstance();
        //设置注册开始时间
        calendar.setTime(date);
        calendar.add(Calendar.SECOND, second);
        return calendar.getTime();
    }

    public static void main(String[] args) {
        System.out.println(getNowYmd());
    }
}
package org.demo.util;

import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
    public static final String DATE_FROMAT_YYYYMMDD = "yyyyMMdd";
    public static final String DATE_FROMAT_YYMMDD = "yyMMdd";
    public static final String TIME_FORMAT_HHMMSS = "HHmmss";

    public DateUtil() {
    }

    public static boolean isWithInDateGap(Date startDate, Date endDate, int gapType, int maxGap) {
        if (startDate == null) {
            throw new IllegalArgumentException("The startDate must not be null");
        } else if (endDate == null) {
            throw new IllegalArgumentException("The endDate must not be null");
        } else if (gapType != 1 && gapType != 2 && gapType != 6) {
            throw new IllegalArgumentException("The value of gapType is invalid");
        } else {
            Calendar start = Calendar.getInstance();
            start.setTime(startDate);
            start.add(gapType, maxGap);
            int compare = start.getTime().compareTo(endDate);
            return compare >= 0;
        }
    }

    public static boolean isWithInDateGap(String startDate, String endDate, int gapType, int maxGap) {
        Date startDateTime = null;
        Date endDateTime = null;

        try {
            startDateTime = DateUtils.parseDate(startDate, new String[]{"yyyyMMdd"});
            endDateTime = DateUtils.parseDate(endDate, new String[]{"yyyyMMdd"});
        } catch (ParseException var7) {
            throw new IllegalArgumentException("日期格式错误,开始日期:" + startDate + ",结束日期:" + endDate, var7);
        }

        return isWithInDateGap(startDateTime, endDateTime, gapType, maxGap);
    }

    public static boolean isWithInDateGap(int startDate, int endDate, int gapType, int maxGap) throws ParseException {
        return isWithInDateGap(DateUtils.parseDate(String.valueOf(startDate), new String[]{"yyyyMMdd"}), DateUtils.parseDate(String.valueOf(endDate), new String[]{"yyyyMMdd"}), gapType, maxGap);
    }

    public static int getCurIntDate() {
        return Integer.parseInt(getCurStringDate());
    }

    public static String getCurStringDate() {
        Date currentDate = new Date();
        SimpleDateFormat formatdate = new SimpleDateFormat("yyyyMMdd");
        return formatdate.format(currentDate);
    }

    public static String getCurDate(String strFormat) {
        Date currentDate = new Date();
        SimpleDateFormat formatdate = new SimpleDateFormat(strFormat);
        return formatdate.format(currentDate);
    }

    public static String getCurStringDateTime() {
        Date currentDate = new Date();
        SimpleDateFormat formatdate = new SimpleDateFormat("yyyyMMddHHmmss");
        return formatdate.format(currentDate);
    }

    public static Long getIntCurIntDateTime() {
        return Long.valueOf(getCurStringDateTime());
    }

    public static String getCurTime() {
        Date currentDate = new Date();
        SimpleDateFormat formatdate = new SimpleDateFormat("HHmmss");
        return formatdate.format(currentDate);
    }

    public static boolean checkDateFormat(int intDate) {
        return checkDateFormat(String.valueOf(intDate));
    }

    public static boolean checkDateFormat(String strDate) {
        return checkDateFormat(strDate, "yyyyMMdd");
    }

    public static boolean checkDateFormat(int intDate, String strFormat) {
        return checkDateFormat(String.valueOf(intDate), "yyyyMMdd");
    }

    public static boolean checkDateFormat(String strDate, String strFormat) {
        try {
            DateUtils.parseDateStrictly(strDate, new String[]{strFormat});
            return true;
        } catch (ParseException var3) {
            return false;
        }
    }

    public static boolean checkTimeFormat(String strDate) {
        return checkTimeFormat(strDate, "HHmmss");
    }

    public static boolean checkTimeFormat(int intDate, String strFormat) {
        return checkTimeFormat(String.valueOf(intDate), "yyyyMMdd");
    }

    public static boolean checkTimeFormat(String strDate, String strFormat) {
        try {
            DateUtils.parseDateStrictly(strDate, new String[]{strFormat});
            return true;
        } catch (ParseException var3) {
            return false;
        }
    }

    public static Date parseDate(String strDate) {
        return parseDate(strDate, "yyyyMMdd");
    }

    public static Date parseDate(String strDate, String strFormat) {
        try {
            return DateUtils.parseDateStrictly(strDate, new String[]{strFormat});
        } catch (ParseException var3) {
            throw new IllegalArgumentException("日期格式错误,日期:" + strDate, var3);
        }
    }

    public static Date parseDate(int intDate, String strFormat) {
        return parseDate(String.valueOf(intDate), strFormat);
    }

    public static Date parseDate(int intDate) {
        return parseDate(String.valueOf(intDate));
    }

    public static String date2String(Date date, String dateFormat) {
        SimpleDateFormat formatdate = new SimpleDateFormat(dateFormat);
        return formatdate.format(date);
    }

    public static String timestamp2String(long date, String dateFormat) {
        SimpleDateFormat formatdate = new SimpleDateFormat(dateFormat);
        return formatdate.format(date);
    }

    public static String date2String(Date date) {
        return date2String(date, "yyyyMMdd");
    }

    public static int date2Int(Date date) {
        String str = date2String(date, "yyyyMMdd");
        return Integer.parseInt(str);
    }

    public static Integer getDateBeforeDay(Integer inputDate, int days) {
        Calendar theCa = Calendar.getInstance();
        theCa.setTime(parseDate(inputDate));
        theCa.add(5, -1 * days);
        Date date = theCa.getTime();
        SimpleDateFormat formatdate = new SimpleDateFormat("yyyyMMdd");
        return Integer.valueOf(formatdate.format(date));
    }

    public static Integer getDateAfterYear(Integer inputDate, int years) {
        Calendar theCa = Calendar.getInstance();
        theCa.setTime(parseDate(inputDate));
        theCa.add(1, years);
        Date date = theCa.getTime();
        SimpleDateFormat formatdate = new SimpleDateFormat("yyyyMMdd");
        return Integer.valueOf(formatdate.format(date));
    }

    public static Integer getDateAfterDay(Integer date, int days) {
        Calendar theCa = Calendar.getInstance();
        theCa.setTime(parseDate(date));
        theCa.add(5, 1 * days);
        Date tempdate = theCa.getTime();
        SimpleDateFormat formatdate = new SimpleDateFormat("yyyyMMdd");
        return Integer.valueOf(formatdate.format(tempdate));
    }
}

猜你喜欢

转载自blog.csdn.net/meser88/article/details/121085076