java时间工具类

在项目中,很多地方需要根据时间获取相应的数据,将时间格式化,或者时间比较等相关操作。一个良好的工具类不仅可以减少代码冗余,还能促进业务处理,加快进度。

/**
 * @author: lxw
 * @Date: 2018/12/25 14:36
 * @Description: 时间工具类
 */
public class DateUtils {
    /**
     * 常用时间格式
     */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public final static String MONTH_PATTERN = "yyyy-MM";

    public final static String DATE_PATTERN = "yyyy-MM-dd";

    public final static String HH_MM_SS = "HH:mm:ss";

    public final static String DATE_PATTERN_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";

    public static String DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS_SSS = "yyyyMMddHHmmssSSS";

    public static String DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS = "yyyyMMddHHmmss";

    /**
     * 日期转换格式数组
     */
    public static String[][] regularExp = new String[][]{

            // 默认格式
            {"\\d{4}-((([0][1,3-9]|[1][0-2]|[1-9])-([0-2]\\d|[3][0,1]|[1-9]))|((02|2)-(([1-9])|[0-2]\\d)))\\s+([0,1]\\d|[2][0-3]|\\d):([0-5]\\d|\\d):([0-5]\\d|\\d)",
                    DATE_TIME_PATTERN},
            // 仅日期格式 年月日
            {"\\d{4}-((([0][1,3-9]|[1][0-2]|[1-9])-([0-2]\\d|[3][0,1]|[1-9]))|((02|2)-(([1-9])|[0-2]\\d)))",
                    DATE_PATTERN},
            //  带毫秒格式
            {"\\d{4}((([0][1,3-9]|[1][0-2]|[1-9])([0-2]\\d|[3][0,1]|[1-9]))|((02|2)(([1-9])|[0-2]\\d)))([0,1]\\d|[2][0-3])([0-5]\\d|\\d)([0-5]\\d|\\d)\\d{1,3}",
                    DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS_SSS}
    };

    /**
     * 日期转换为String类型
     *
     * @param date    日期
     * @param pattern 获取格式
     * @return String
     */
    public static String format(Date date, String pattern) {
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }

    /**
     * 日期转换为String类型,并添加或减少相应的天数
     *
     * @param date    日期
     * @param pattern 获取格式
     * @param amount  天数
     * @return String
     */
    public static String format(Date date, String pattern, int amount) {
        if (date != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_MONTH, amount);
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(calendar.getTime());
        }
        return null;
    }

    /**
     * 字符串转换成日期
     *
     * @param strDate 日期字符串
     * @param pattern 日期的格式
     * @return data
     */
    public static Date stringToDate(String strDate, String pattern) {
        if (StringUtils.isBlank(strDate)) {
            return null;
        }

        DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
        return fmt.parseLocalDateTime(strDate).toDate();
    }

    /**
     * 两个时间之间的天数
     *
     * @param date1
     * @param date2
     * @param pattern 格式
     * @return 天数
     */
    public static long getDays(String date1, String date2, String pattern) {
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        if (date1 == null || date1.equals("")) {
            return 0;
        }
        if (date2 == null || date2.equals("")) {
            return 0;
        }
        try {
            Date date = formatter.parse(date1);
            Date newDate = formatter.parse(date2);
            return (date.getTime() - newDate.getTime()) / (24 * 60 * 60 * 1000);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 产生周序列,即得到当前时间所在的年度是第几周
     *
     * @return
     */
    public static String getSeqWeek() {
        Calendar c = Calendar.getInstance(Locale.CHINA);
        String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));
        if (week.length() == 1) {
            week = "0" + week;
        }
        return week;
    }

    /**
     * 日期格式字符串转换成时间戳
     *
     * @param date_str 字符串日期
     * @param format   日期格式,如:yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String dateTimeStamp(String date_str, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return String.valueOf(sdf.parse(date_str).getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取日期的格式
     *
     * @param date_str 日期格式字符串
     * @return 当前日期格式
     */
    public static String getDateFormat(String date_str) {
        String style = null;
        if (org.springframework.util.StringUtils.isEmpty(date_str)) {
            return null;
        }
        boolean b = false;
        for (int i = 0; i < regularExp.length; i++) {
            b = date_str.matches(regularExp[i][0]);
            if (b) {
                style = regularExp[i][1];
            }
        }
        if (org.springframework.util.StringUtils.isEmpty(style)) {
            return null;
        }
        return style;
    }

    /**
     * 转换为时间类型格式
     *
     * @param strDate 日期
     * @return
     */
    public static Date strToDate(String strDate) {
        try {
            String strType = getDateFormat(strDate);
            if (strType == null) {
                return null;
            }
            SimpleDateFormat sf = new SimpleDateFormat(strType);
            return new Date((sf.parse(strDate).getTime()));
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取两个字符串时间差
     *
     * @param beginTime 开始时间
     * @param endTime   结束时间
     * @return xx小时xx分钟
     */
    public static String timeLength(String beginTime, String endTime) {
        if (beginTime == null || "".equals(beginTime)) {
            return "";
        }
        if (endTime == null || "".equals(endTime)) {
            return "";
        }
        Date begin = DateUtils.strToDate(beginTime);
        Date end = DateUtils.strToDate(endTime);
        if (begin == null || end == null) {
            return "";
        }
        try {
            //除以1000是为了转换成秒
            long between = (end.getTime() - begin.getTime()) / 1000;
            int day = (int) between / (24 * 3600);
            int hour = (int) between % (24 * 3600) / 3600;
            int minute = (int) between % 3600 / 60;
            int currentHour = day * 24 + hour;
            return currentHour + "小时" + minute + "分钟";
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 判断是否润年
     *
     * @param date 日期
     * @return boolean
     */
    public static boolean isLeapYear(Date date) {
        /**
         * 1.被400整除是闰年
         * 2.不能被4整除则不是闰年
         * 3.能被4整除同时不能被100整除则是闰年
         * 4.能被4整除同时能被100整除则不是闰年
         */
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        gc.setTime(date);
        int year = gc.get(Calendar.YEAR);
        if ((year % 400) == 0) {
            return true;
        } else if ((year % 4) == 0) {
            if ((year % 100) == 0) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    /**
     * 取得当前时间生成格式为yyyymmddhhmmss+k位随机数
     *
     * @param k 随机数位数
     */
    public static String getNo(int k) {
        Date date = new Date();
        return format(date, DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS) + getRandom(k);
    }

    /**
     * 返回一个随机数
     *
     * @param num 随机生成的位数
     * @return
     */
    public static String getRandom(int num) {
        Random random = new Random();
        if (num == 0) {
            return "";
        }
        String randomNum = "";
        for (int i = 0; i < num; i++) {
            //取0-9的随机数进行拼接
            randomNum += random.nextInt(9);
        }
        return randomNum;
    }

  /**
     * 根据周数,获取开始日期、结束日期
     *
     * @param week 周期  0本周,-1上周,-2上上周,1下周,2下下周
     * @return 返回date[0]开始日期、date[1]结束日期
     */
    public static Date[] getWeekStartAndEnd(int week) {
        DateTime dateTime = new DateTime();
        LocalDate date = new LocalDate(dateTime.plusWeeks(week));

        date = date.dayOfWeek().withMinimumValue();
        Date beginDate = date.toDate();
        Date endDate = date.plusDays(6).toDate();
        return new Date[]{beginDate, endDate};
    }

    /**
     * 对日期的【秒】进行加/减
     *
     * @param date    日期
     * @param seconds 秒数,负数为减
     * @return 加/减几秒后的日期
     */
    public static Date addDateSeconds(Date date, int seconds) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusSeconds(seconds).toDate();
    }

    /**
     * 对日期的【分钟】进行加/减
     *
     * @param date    日期
     * @param minutes 分钟数,负数为减
     * @return 加/减几分钟后的日期
     */
    public static Date addDateMinutes(Date date, int minutes) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusMinutes(minutes).toDate();
    }

    /**
     * 对日期的【小时】进行加/减
     *
     * @param date  日期
     * @param hours 小时数,负数为减
     * @return 加/减几小时后的日期
     */
    public static Date addDateHours(Date date, int hours) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusHours(hours).toDate();
    }

    /**
     * 对日期的【天】进行加/减
     *
     * @param date 日期
     * @param days 天数,负数为减
     * @return 加/减几天后的日期
     */
    public static Date addDateDays(Date date, int days) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusDays(days).toDate();
    }

    /**
     * 对日期的【周】进行加/减
     *
     * @param date  日期
     * @param weeks 周数,负数为减
     * @return 加/减几周后的日期
     */
    public static Date addDateWeeks(Date date, int weeks) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusWeeks(weeks).toDate();
    }

    /**
     * 对日期的【月】进行加/减
     *
     * @param date   日期
     * @param months 月数,负数为减
     * @return 加/减几月后的日期
     */
    public static Date addDateMonths(Date date, int months) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusMonths(months).toDate();
    }

    /**
     * 对日期的【年】进行加/减
     *
     * @param date  日期
     * @param years 年数,负数为减
     * @return 加/减几年后的日期
     */
    public static Date addDateYears(Date date, int years) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusYears(years).toDate();
    }

    /**
     * 比较时间大小
     *
     * @param exprtime 时间1
     * @param times    时间2
     * @return 0:时间相等 1;时间1在时间2之后 -1:时间1在时间2之前
     */
    public static int compareDate(String exprtime, String times) {
        int result = 0;
        //判断时间大小
        if (exprtime != null && !"".equals(exprtime)) {
            DateFormat dateFormat = new SimpleDateFormat(DATE_TIME_PATTERN);
            try {
                Date d1 = dateFormat.parse(exprtime);
                Date d2 = dateFormat.parse(times);
                if (d1.getTime() > d2.getTime()) {
                    System.out.println(d1 + "在" + d2 + "之后");
                    result = 1;
                } else if (d1.getTime() < d2.getTime()) {
                    result = -1;
                    System.out.println(d1 + "在" + d2 + "之前");
                } else {
                    System.out.println(d1 + "=" + d2);
                }
            } catch (ParseException e) {
                e.printStackTrace();
                System.out.println("方法——compareDate异常");
            }
        }
        return result;
    }

    /**
     * 获取距离现在的天数
     *
     * @param exprtime 某天的时间字符串
     * @return 天数
     */
    public static long getDays(String exprtime) {
        Date begin = DateUtils.strToDate(format(new Date(), DATE_TIME_PATTERN));
        Date end = DateUtils.strToDate(exprtime);
        long between = (end.getTime() - begin.getTime()) / 1000;
        int day = (int) between / (24 * 3600);
        return day;
    }

测试类方法:

 public static void main(String[] args) {
          Date date = new Date();
        String dateString = DateUtils.format(date, DATE_TIME_PATTERN);
        System.out.println("时间格式转换为:" + dateString);

        String tomorrow = DateUtils.format(date, DATE_TIME_PATTERN, 1);
        System.out.println("明天日期:" + tomorrow);

        Date stringToDate = DateUtils.stringToDate(dateString, DATE_TIME_PATTERN);
        System.out.println("当天日期格式:" + stringToDate);

        boolean flag = DateUtils.isLeapYear(date);
        System.out.println("当前是否为闰年:" + flag);

        long days = DateUtils.getDays(tomorrow, dateString, DATE_PATTERN);
        System.out.println("天数相差:" + days + " 天");

        String getSeqWeek = DateUtils.getSeqWeek();
        System.out.println("今年第 " + getSeqWeek + " 周");

        String randomNum = DateUtils.getNo(4);
        System.out.println("编号:" + randomNum);

        String dateTimeStamp = DateUtils.dateTimeStamp(dateString, DATE_TIME_PATTERN);
        System.out.println("当期时间戳:" + dateTimeStamp);

        String timeLength = DateUtils.timeLength(dateString, tomorrow);
        System.out.println("相差时间:" + timeLength);

        String getDateFormat = DateUtils.getDateFormat(dateString);
        System.out.println("当前日期格式:" + getDateFormat);

        String stmpString = DateUtils.stampToDate("1545732716");
        System.out.println("当前日期:" + stmpString);

        String stmpLong = DateUtils.stampToDate(1545732716L);
        System.out.println("当前日期:" + stmpLong);

        long day = DateUtils.getDays("2019-01-01 18:20:20");
        System.out.println("距离当前时间:" + day + "天");
    }

输出结果:

时间格式转换为:2018-12-25 18:21:23
明天日期:2018-12-26 18:21:23
当天日期格式:Tue Dec 25 18:21:23 CST 2018
当前是否为闰年:false
天数相差:1 天
今年第 52 周
编号:201812251821237084
当期时间戳:1545733283
相差时间:24小时0分钟
当前日期格式:yyyy-MM-dd HH:mm:ss
当前日期:1970-01-19 05:22:12
当前日期:1970-01-19 05:22:12
距离当前时间:6天

该类希望可以满足大部分的业务需求,后续如果还有会继续添加到下文中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值