JAVA时间工具类,在维护的项目里的

package com.inspur.jobSchedule.util;

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

import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * 日期处理通用类
 *
 * @author
 * @version 1.0
 */
public final class DateUtil extends DateUtils {

    private static Logger logger = Logger.getLogger("DateUtil");

    /**
     * 返回date1 - date2 的分钟数
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 相隔分钟数
     */
    public static long getMinites(String date1, String date2) {
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

        long millSec = 0L;
        long diffMins = 0L;
        try {
            millSec = dfs.parse(date1).getTime() - dfs.parse(date2).getTime();
            millSec = Math.abs(millSec);
            diffMins = (millSec / 1000) / 60;
        } catch (ParseException e) {
            logger.error("getMinites exception:" + e.getMessage());
        }
        return diffMins;
    }

    /**
     * 返回date1 - date2 的分钟数
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 相隔分钟数
     */
    public static long getMins(String date1, String date2) {
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        long millSec = 0L;
        long diffMins = 0L;
        try {
            millSec = dfs.parse(date1).getTime() - dfs.parse(date2).getTime();
            millSec = Math.abs(millSec);
            diffMins = (millSec / 1000) / 60;
        } catch (ParseException e) {
            logger.error("getMins exception:" + e);
        }
        return diffMins;
    }

    /**
     * 返回date1 - date2 的秒数
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 相隔秒数
     */
    public static long getDiffSeconds(String date1, String date2) {
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        long millSec = 0L;
        long diffSeconds = 0L;
        try {
            millSec = dfs.parse(date1).getTime() - dfs.parse(date2).getTime();
            millSec = Math.abs(millSec);
            diffSeconds = millSec / 1000;
        } catch (ParseException e) {
            // e.printStackTrace();
            logger.error("getDiffSeconds exception:" + e);
        }
        return diffSeconds;
    }

    /**
     * 格式化日期 : yyyy-MM-dd HH:mm:ss
     *
     * @param date 日期
     * @return 日期字符串,如果date为空返回空串("")
     */
    public static String getFormatDateString(Date date) {
        if (date == null) {
            return "";
        }

        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    }

    /**
     * 任务调度 格式化日期 : yyyy-MM-dd HH:mm:ss.SSS
     *
     * @param date
     * @return 日期字符串,如果date为空返回空串("")
     * @since 1.0
     */
    public static String getFormatDateForSchedule(Date date) {
        if (date == null) {
            return "";
        }

        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(date);
    }

    /**
     * 格式化日期 : yyyy-MM-dd HH:mm
     *
     * @param date 日期
     * @return 日期字符串,如果date为空返回空串("")
     */
    public static String getFormatDateTimeString(Date date) {
        if (date == null) {
            return "";
        }
        return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
    }

    /**
     * 格式化日期 : yyyy-MM-dd
     *
     * @param date 日期
     * @return 日期字符串,如果为空返回空串("")
     */
    public static String getDateString(Date date) {
        if (date == null) {
            return "";
        }

        return new SimpleDateFormat("yyyy-MM-dd").format(date);
    }

    /**
     * 格式化时间 : HH:mm:ss
     *
     * @param date 日期对象
     * @return 格式化日期字符串
     */
    public static String getTimeString(Date date) {
        if (date == null) {
            return "";
        }

        return new SimpleDateFormat("HH:mm:ss").format(date);
    }

    /**
     * 由字符串转换为日期类型
     *
     * @param str    日期字符串
     * @param format 格式化字符串
     * @return 日期对象
     */
    public static Date getDate(String str, String format) {
        try {
            return new SimpleDateFormat(format).parse(str);
        } catch (ParseException e) {
            return null;
        } catch (RuntimeException e) {
            return null;
        }
    }

    /**
     * 获取日期对应的时间,其中年月日为当前的年月日,时间为参数中的时间
     *
     * @param time 时间
     * @return 日期
     */
    public static Date getDateFromTime(Time time) {
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(new SimpleDateFormat("HH:mm:ss").parse(time.toString()));
        } catch (ParseException e) {
            logger.error("getDateFromTime exception:" + e.getMessage());
            return null;
        } catch (RuntimeException e) {
            logger.error("getDateFromTime exception:" + e);
            return null;
        }
        Calendar cal = Calendar.getInstance();
        c.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                cal.get(Calendar.DATE));
        return c.getTime();
    }

    /**
     * 返回毫秒级别数据
     *
     * @param date 日期对象
     * @return mmssSSS 格式时间
     */
    public static String getmmssSSS(Date date) {
        return new SimpleDateFormat("mmssSSS").format(date);
    }

    /**
     * 日期格式化(业务包使用,勿删)
     *
     * @param sDate 原始串
     * @param sFmt  格式
     * @return 输出
     */
    public static Date toDate(String sDate, String sFmt) {
        Date dt = null;
        try {
            dt = new SimpleDateFormat(sFmt).parse(sDate);
        } catch (ParseException e) {
            return dt;
        }
        return dt;
    }

    /**
     * 将日期格式化为长格式(业务包使用,勿删)
     *
     * @param dateDate 原始日期
     * @return 输出
     */
    public static String dateToStrLong(Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(dateDate);
        return dateString;
    }

    /**
     * 将日期格式化为长格式到毫秒(业务包使用,勿删)
     *
     * @param dateDate 原始日期
     * @return 输出
     */
    public static String dateToStrLongSSS(Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ssSSS");
        String dateString = formatter.format(dateDate);
        return dateString;
    }

    /**
     * FormatDateTime(业务包使用,勿删)
     *
     * @param strDateTime 原始日期
     * @param strFormat   转换格式
     * @return 转换结果
     */
    public static String formatDateTime(String strDateTime, String strFormat) {
        String sDateTime = strDateTime;
        Calendar cal = parseDateTime(strDateTime);
        SimpleDateFormat sdf = null;
        sdf = new SimpleDateFormat(strFormat);
        sDateTime = sdf.format(cal.getTime());
        return sDateTime;
    }

    /**
     * 将日期解析为calendar对象(业务包使用,勿删)
     *
     * @param baseDate 原始日期
     * @return calendar对象
     */
    public static Calendar parseDateTime(String baseDate) {
        Calendar cal = null;
        cal = new GregorianCalendar();
        int yy = Integer.parseInt(baseDate.substring(0, 4));
        int mm = Integer.parseInt(baseDate.substring(5, 7)) - 1;
        int dd = Integer.parseInt(baseDate.substring(8, 10));
        int hh = 0;
        int mi = 0;
        int ss = 0;
        if (baseDate.length() > 12) {
            hh = Integer.parseInt(baseDate.substring(11, 13));
            mi = Integer.parseInt(baseDate.substring(14, 16));
            ss = Integer.parseInt(baseDate.substring(17, 19));
        }
        cal.set(yy, mm, dd, hh, mi, ss);
        return cal;
    }

    /**
     * 获取指定格式的当前时间(业务包使用,勿删)
     *
     * @param sformat 日期格式
     * @return 格式化日期串
     */
    public static String getUserDate(String sformat) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(sformat);
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * @param mss 要转换的毫秒数 单位为英文单位 days,hour,分钟,秒
     * @return 该毫秒数转换为 * days * hours * minutes * seconds 后的格式
     */
    public static String formatDuring(long mss) {
        long days = mss / (1000 * 60 * 60 * 24);
        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (mss % (1000 * 60)) / 1000;
        return days + " days " + hours + " hours " + minutes + " minutes "
                + seconds + " seconds ";
    }

    /**
     * @param mss 要转换的毫秒数 单位为汉字 天,小时,分钟,秒
     * @return 该毫秒数转换为 * days * hours * minutes * seconds 后的格式
     */
    public static String formatDuringCN(long mss) {
        long days = mss / (1000 * 60 * 60 * 24);
        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (mss % (1000 * 60)) / 1000;
        return days + " 天 " + hours + " 小时 " + minutes + " 分" + seconds + " 秒 ";
    }

    /**
     * 运行时间计算 任务调度专用
     *
     * @param mss
     * @return
     * @since 1.0
     */
    public static String formatDurationCN(long mss) {
        long days = mss / (1000 * 60 * 60 * 24);
        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (mss % (1000 * 60)) / 1000;
        long msec = mss % 1000;
        String result = msec + "毫秒";
        if (seconds != 0L) {
            result = seconds + "秒" + result;
        }
        if (minutes != 0L) {
            result = minutes + "分" + result;
        }
        if (hours != 0L) {
            result = hours + "小时" + result;
        }
        if (days != 0L) {
            result = days + "天" + result;
        }
        return result;
    }

    /**
     * @param begin 时间段的开始
     * @param end   时间段的结束
     * @return 输入的两个Date类型数据之间的时间间格用* days * hours * minutes * seconds的格式展示
     */
    public static String formatDuring(Date begin, Date end) {
        return formatDuring(end.getTime() - begin.getTime());
    }

    /**
     * @param begin 时间段的开始
     * @param end   时间段的结束
     * @return 输入的两个Date类型数据之间的时间间格用* days * hours * minutes * seconds的格式展示
     */
    public static String formatDuringCN(Date begin, Date end) {
        return formatDuringCN(end.getTime() - begin.getTime());
    }

    /**
     * 任务调度返回任务运行时间
     *
     * @param begin 时间段的开始
     * @param end   时间段的结束
     * @return
     * @since 1.0
     */
    public static String formatDurationCN(Date begin, Date end) {
        return formatDurationCN(end.getTime() - begin.getTime());
    }

    /**
     * 格式化日期 : yyyy-MM-dd HH:mm:ss
     *
     * @param date 日期
     * @return 返回年 yyyy
     */
    public static String getFormatDateYear(Date date) {
        if (date == null) {
            return "";
        }

        return new SimpleDateFormat("yyyy").format(date);
    }

    /**
     * 格式化日期 : yyyy-MM-dd HH:mm:ss
     *
     * @param date 日期
     * @return 返回年 yyyy
     */
    public static String getFormatDateMonth(Date date) {
        if (date == null) {
            return "";
        }

        return new SimpleDateFormat("yyyy-MM").format(date);
    }

    /**
     * 返回上一个月的日期 yyyy-MM
     *
     * @param date 日期
     * @return 返回年 yyyy
     */
    public static String getFormatDateLastMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -1);
        Date newDate = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM").format(newDate);
    }

    /**
     * 返回下一个月的日期 yyyy-MM
     *
     * @param date 日期
     * @return 返回年 yyyy
     */
    public static String getFormatDateNextMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1);
        Date newDate = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM").format(newDate);
    }

    public static String getLastNDays(Date date, int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -days);
        Date newDate = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(newDate);
    }

    public static String getLastNHours(Date date, int hours) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR_OF_DAY, -hours);
        Date newDate = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(newDate);
    }

    public static String getLastNMins(Date date, int minutes) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, -minutes);
        Date newDate = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(newDate);
    }

    public static String getLastNSecs(Date date, int seconds) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.SECOND, -seconds);
        Date newDate = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(newDate);
    }

    public static String getLastNMinsWithParse(Date date, int minutes,
                                               String parse) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, -minutes);
        Date newDate = calendar.getTime();
        return new SimpleDateFormat(parse).format(newDate);
    }

    /**
     * 获取最近的正好5分钟的时间
     *
     * @return
     */
    public static Date getLastJust5Min() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)
                - calendar.get(Calendar.MINUTE) % 5);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date newDate = calendar.getTime();
        return newDate;
    }

    /**
     * 获取最近的正好5分钟的时间字符串
     *
     * @return
     */
    public static String getLastJust5MinStr() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)
                - calendar.get(Calendar.MINUTE) % 5);
        Date newDate = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:00").format(newDate);
    }

    /**
     * 获取最近的正好15分钟的时间字符串
     *
     * @return
     */
    public static String getLastJust15MinStr() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)
                - calendar.get(Calendar.MINUTE) % 15);
        Date newDate = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:00").format(newDate);
    }

    /**
     * 格式化日期 : yyyy-MM-dd HH:mm:ss
     *
     * @param time 这里为毫秒级的时间类型
     * @return 返回格式化的日期
     * @since 1.0
     */
    public static String getFormatDateString(long time) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date(time));
    }

    /**
     * 比较两个日期是否相等
     *
     * @param sourceDate
     * @param targetDate
     * @return 如果相等返回true 不相等返回false
     * @since 1.0
     */
    public static boolean compareDate(String sourceDate, String targetDate) {
        boolean flag = false;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date dt1 = df.parse(sourceDate);
            Date dt2 = df.parse(targetDate);
            if (dt1.getTime() > dt2.getTime()) {
            } else if (dt1.getTime() < dt2.getTime()) {
            } else {
                flag = true;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return flag;
    }

    /**
     * 比较两个日期相等
     *
     * @param sourceDate
     * @param targetDate
     * @return
     * @since 1.0
     */
    public static boolean compareDate(Date sourceDate, Date targetDate) {
        boolean flag = false;
        if (null == sourceDate && null == targetDate) {
            flag = true;
        }
        if (null != sourceDate && null != targetDate) {
            try {

                if (sourceDate.getTime() > targetDate.getTime()) {
                } else if (sourceDate.getTime() < targetDate.getTime()) {
                } else {
                    flag = true;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 当前时间前移30分钟
     *
     * @param endtime
     * @return
     * @Time 2018年8月21日
     * @author guoqiaozhi
     */
    public static String getStarttimeHhour(String endtime) {
        Date startDate = DateUtil.addMinutes(DateUtil.getDate(endtime, "yyyy-MM-dd HH:mm:ss"), -30);
        return DateUtil.getFormatDateString(startDate);
    }

    /**
     * 当前时间前移一小时
     *
     * @param endtime
     * @return
     * @Time 2018年8月21日
     * @author guoqiaozhi
     */
    public static String getStarttimeHour(String endtime) {
        Date startDate = DateUtil.addHours(DateUtil.getDate(endtime, "yyyy-MM-dd HH:mm:ss"), -1);
        return DateUtil.getFormatDateString(startDate);
    }

    /**
     * 当前时间前移一天
     *
     * @param endtime
     * @return
     * @Time 2018年8月21日
     * @author guoqiaozhi
     */
    public static String getStarttimeDay(String endtime) {
        Date startDate = DateUtil.addDays(DateUtil.getDate(endtime, "yyyy-MM-dd HH:mm:ss"), -1);
        return DateUtil.getFormatDateString(startDate);
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值