Java的一些对时间操作的工具类

懒驴 2021年12月10日 1,746次浏览

分享一下本人在学习中积累的一些对时间操作的方法,Java代码如下:


import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/***
 * 时间工具类
 */
public class DateHelper {


    /***
     * 1.获取系统时间的前一天
     * @return 返回格式为:2018-01-01
     */
    public static String getYesterdayDate(){
        try {
            Date dNow = new Date(); //当前时间
            Date dBefore = new Date();
            Calendar calendar = Calendar.getInstance(); //得到日历
            calendar.setTime(dNow);//把当前时间赋给日历
            calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
            dBefore = calendar.getTime(); //得到前一天的时间

            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
            String defaultStartDate = sdf.format(dBefore); //格式化前一天
            return defaultStartDate;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    /***
     * 1.1.获取系统时间的前N天
     * @return 返回格式为:2018-01-01
     */
    public static String getYesterdayNDayDate(int n){
        try {
            if(n<=0){
                n=0;
            }
            Date dNow = new Date(); //当前时间
            Date dBefore = new Date();
            Calendar calendar = Calendar.getInstance(); //得到日历
            calendar.setTime(dNow);//把当前时间赋给日历
            calendar.add(Calendar.DAY_OF_MONTH, -n); //设置为前一天
            dBefore = calendar.getTime(); //得到前一天的时间

            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
            String defaultStartDate = sdf.format(dBefore); //格式化前一天
            return defaultStartDate;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    /***
     * 1.2.获取系统时间的前N天
     * @return 返回格式为:2018-01-01
     */
    public static String getYesterdayNDayDateTwo(int n){
        try {
            if(n<=0){
                n=0;
            }
            Date dNow = new Date(); //当前时间
            Date dBefore = new Date();
            Calendar calendar = Calendar.getInstance(); //得到日历
            calendar.setTime(dNow);//把当前时间赋给日历
            calendar.add(Calendar.DAY_OF_MONTH, -n); //设置为前一天
            dBefore = calendar.getTime(); //得到前一天的时间

            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置时间格式
            String defaultStartDate = sdf.format(dBefore); //格式化前一天
            return defaultStartDate;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    /***
     *2.获取系统当前时间:2016-08-08 24:00:00
     * @return
     */
    public static String getNewData(){
        Date date=new Date();   //获取当前时间
        return String.format("%tF %tT", date,date);
    }

    /***
     *2.获取系统当前时间:2016-08-08@24_00_:00
     * @return
     */
    public static String getNewDataFour(){
        Date date=new Date();   //获取当前时间
        String str=String.format("%tF@%tT", date,date);
        str=str.replace(":", "_");
        return str;
    }

    /***
     *2.3.获取系统当前时间:2016-08-08 24:00
     * @return
     */
    public static String getNewDataTwo(){
        DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date=new Date();   //获取当前时间
        return dFormat.format(date);
    }

    /***
     *2.4.获取系统当前时间:201608082400
     * @return
     */
    public static String getNewDatayyyyMMDD(){
        DateFormat dFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Date date=new Date();   //获取当前时间
        return dFormat.format(date);
    }

    /***
     *2.1.获取系统当前时间:2016-08-08
     * @return
     */
    public static String getNewDayData(){
        Date date=new Date();   //获取当前时间
        return String.format("%tF", date);
    }

    /***
     * 3.字符串日期格式计算出相差天数
     * @param  begintime 开始时间 2018-01-01
     * @param  endstime  结束时间 201-01-20
     * @return
     * @throws ParseException
     */
    public static int getDaysBetween(String begintime,String endstime) throws ParseException{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(begintime));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(endstime));
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /***
     * 4.字符日期转换为Date日期
     * @param strDate 字符串日期格式 2018-01-01
     * @return	返回 java.util.Date;类型时间
     */
    public static Date stringDateToDate(String strDate){
        SimpleDateFormat lsdStrFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date strD = lsdStrFormat.parse(strDate);
            return strD;
        } catch (ParseException e) {
            e.printStackTrace();
            return new Date();
        }
    }

    /***
     * 4.Date格式日期转换为字符串格式:2016-07-06
     * @param date Date格式时间
     */
    public static String getDateToStr(Date date) {
        //格式:2016-07-06
        DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dFormat.format(date);
    }
    /***
     * 4.2.Date格式日期转换为字符串格式:2016-07-06 00:00:00
     * @param date Date格式时间
     */
    public static String getDateToStrTwo(Date date) {
        //格式:2016-07-06
        DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dFormat.format(date);
    }


    /***
     * 4.3.Date格式日期转换为字符串格式:2016-07-06 00:00:00
     * @param date Date格式时间
     */
    public static Date getStrDateToDate(String date) {
        SimpleDateFormat lsdStrFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date strD = lsdStrFormat.parse(date);
            return strD;
        } catch (ParseException e) {
            e.printStackTrace();
            return new Date();
        }
    }

    /***
     * 4.2.获取当前Date格式的时间
     * 字符串日期格式 2018-01-01 00:00:00
     * @return	返回 java.util.Date;类型时间
     */
    public static Date getNowDateToDate(){
        SimpleDateFormat lsdStrFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date strD = lsdStrFormat.parse(getNewData());
            return strD;
        } catch (ParseException e) {
            e.printStackTrace();
            return new Date();
        }
    }

    /***
     * 5.获取一段时间之间的每一天日期
     * @param dBeginStr	开始时间
     * @param dEndStr	结束时间
     * @return
     */
    public static List<String> findDates(String dBeginStr, String dEndStr) {
        try {
            Date dBegin=DateHelper.stringDateToDate(dBeginStr);
            Date dEnd=DateHelper.stringDateToDate(dEndStr);
            List<String> lDate = new ArrayList<String>();
            lDate.add(dBeginStr);
            Calendar calBegin = Calendar.getInstance();
            //使用给定的 Date 设置此 Calendar 的时间
            calBegin.setTime(dBegin);
            Calendar calEnd = Calendar.getInstance();
            //使用给定的 Date 设置此 Calendar 的时间
            calEnd.setTime(dEnd);
            //测试此日期是否在指定日期之后
            while (dEnd.after(calBegin.getTime()))  {
                // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
                calBegin.add(Calendar.DAY_OF_MONTH, 1);
                lDate.add(DateHelper.getDateToStr(calBegin.getTime()));
            }
            return lDate;
        } catch (Exception e) {
            return null;
        }

    }

    /***
     * 6.获取当前小时数前N小时的时间
     *  ageHour
     * @return 格式是二位数组的形式 年月日:str[0][0] 小时:str[0][1]
     */
    public static String[][] getNowDayHour(int ageHour){
        String[][] str=new String[][]{{DateHelper.getNewDayData(),DateHelper.getNowHour(ageHour)}};
        try {
            if(ageHour<=0){
                ageHour=0;
            }

            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - ageHour);
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
            str[0][0]=df1.format(calendar.getTime());//年月日
            SimpleDateFormat df2 = new SimpleDateFormat("HH"); 				//小时数
            str[0][1]=df2.format(calendar.getTime());//小时数

        } catch (Exception e) {
            System.out.println(e);
            return str;
        }
        return str;
    }

    /***
     * 7.获取当前小时前N小时的小时数
     */
    public static String getNowHour(int hour){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - hour);
        SimpleDateFormat df2 = new SimpleDateFormat("HH"); 				//小时数
        return df2.format(calendar.getTime());
    }

    /***
     * 7.2.获取当前时间的前N小时的时间
     */
    public static String getBeforeHourToNowDate(Integer hour) throws Exception{
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - hour);
        DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dFormat.format(calendar.getTime());
    }


    /***
     * 8.获取指定时间的前N天
     * 参数格式:2018-01-01
     * -n表示前N天,n表示后N天
     */
    public static String getNowAgoDayDate(String day,int n){
        // 时间表示格式可以改变,yyyyMMdd需要写例如20160523这种形式的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 将字符串的日期转为Date类型,ParsePosition(0)表示从第一个字符开始解析
        Date date = sdf.parse(day, new ParsePosition(0));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // add方法中的第二个参数n中,正数表示该日期后n天,负数表示该日期的前n天
        calendar.add(Calendar.DATE, n);
        Date date1 = calendar.getTime();
        String out = sdf.format(date1);
        //System.out.println(out);
        return out;
    }
    /***
     * 8.2.获取指定时间的前N天
     * 参数格式:2018-01-01 10:08:03
     * -n表示前N天,n表示后N天
     */
    public static String getNowAgoDayDateTwo(String day,int n){
        // 时间表示格式可以改变,yyyyMMdd需要写例如20160523这种形式的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 将字符串的日期转为Date类型,ParsePosition(0)表示从第一个字符开始解析
        Date date = sdf.parse(day, new ParsePosition(0));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // add方法中的第二个参数n中,正数表示该日期后n天,负数表示该日期的前n天
        calendar.add(Calendar.DATE, n);
        Date date1 = calendar.getTime();
        String out = sdf.format(date1);
        //System.out.println(out);
        return out;
    }

    /***
     * 9.返回当前时间戳
     * @return
     */
    public static long getSimpDateMillis(){
        Date date=new Date();
        //return System.currentTimeMillis();
        return date.getTime();
    }

    /***
     * 9.2.时间装换为时间戳
     */
    public static long dateToStamp(String s) throws ParseException{
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        return ts;
    }


    /***
     * 10.获取当前时间 格式: 2018-08-08 08:08
     */
    public static String getNowTimeminus(){
        DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return dFormat.format(new Date());
    }

    /***
     * 11.获取用户的前后N分钟的时间  格式为:2018-08-08 08:08
     * @param n 前N分钟数       正n表示后n分钟,负n表示前n分钟
     * @return
     */
    public static String getNowAgoTimeminus(int n){
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, n);// n分钟时间
        Date beforeD = beforeTime.getTime();
        String before = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(beforeD);  // n分钟时间
        return before;
    }


    /***
     * 11.2.获取用户的前后N分钟的时间  格式为:2018-08-08 08:08
     * @param n 前N分钟数       正n表示后n分钟,负n表示前n分钟
     * @return
     */
    public static String getNowAgoTimeminusTwo(int n){
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, n);// n分钟时间
        Date beforeD = beforeTime.getTime();
        String before = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(beforeD);  // n分钟时间
        return before;
    }


    /***12.获取当前Date格式时间***/
    public static Date getThisDate() throws Exception{
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date end = dfs.parse(getNewData());		//当前时间
        return end;
    }

    /***
     * 13.计算两个时间相差的分钟数
     *  endDate
     *  nowDate
     * @return
     */
    public static long getDatePoor(Date beginDate, Date endDate) {
        long diff = endDate.getTime() - beginDate.getTime();
        //相差的秒数
        int yu=(int) (diff%60);
        if(yu>0) {
            diff=diff/1000/60;
            diff=diff+1;
        }else {
            diff=diff/1000/60;
        }
        return diff;
    }

    /***
     * 13.3.计算两个时间相差的分钟数
     * endDate
     * nowDate
     * @param x   忽略的秒数
     * @return
     */
    public static long getDatePoorMiao(Date beginDate, Date endDate,int x) {
        long diff = endDate.getTime() - beginDate.getTime();

        //相差的秒数
        int miao=(int) (diff/1000);
        if(miao>=x) {
            if(miao%60>0) {
                diff=diff/1000/60;
                diff=diff+1;
            }else {
                diff=diff/1000/60;
            }
        }else {
            return -1;
        }
        return diff;
    }

    /***
     * 13.4.计算两个时间相差的分钟数
     * endDate
     * nowDate
     * x   忽略的秒数
     * @return
     */
    public static long getDatePoorMiaoFour(Date beginDate, Date endDate,int x) {
        long diff = endDate.getTime() - beginDate.getTime();

        //相差的秒数
        int miao=(int) (diff/1000);
        if(miao>=x) {
            if(miao%60>0) {
                diff=diff/1000/60;
            }else {
                diff=diff/1000/60;
            }
        }else {
            return -1;
        }
        return diff;
    }

    /***
     * 13.2.计算两个时间相差的天数
     * endDate
     * nowDate
     * @return
     */
    public static int getDateDayPoor(Date beginDate, Date endDate) {
        Calendar aCalendar = Calendar.getInstance();
        aCalendar.setTime(beginDate);
        int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
        aCalendar.setTime(endDate);
        int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
        int days=day2-day1;
        return days;
    }


    /***
     * 14.一周的时间,隔年的计算
     * @param dBeginStr	开始时间
     * @param dEndStr	结束时间
     * @return
     */
    public static List<String> oneWeekDates(String dBeginStr, String dEndStr) {
        try {
            Date dBegin=DateHelper.stringDateToDate(dBeginStr);
            Date dEnd=DateHelper.stringDateToDate(dEndStr);
            List<String> lDate = new ArrayList<String>();
            lDate.add(dBeginStr);
            Calendar calBegin = Calendar.getInstance();
            //使用给定的 Date 设置此 Calendar 的时间
            calBegin.setTime(dBegin);
            Calendar calEnd = Calendar.getInstance();
            //使用给定的 Date 设置此 Calendar 的时间
            calEnd.setTime(dEnd);
            //测试此日期是否在指定日期之后
            while (dEnd.after(calBegin.getTime()))  {
                // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
                calBegin.add(Calendar.DAY_OF_MONTH, 1);
                lDate.add(DateHelper.getDateToStr(calBegin.getTime()));
            }
            //当前年
            String year=DateUtil.format(DateHelper.getNowDateToDate(), "yyyy");
            for(String s:lDate){	//移除隔年的日期
                if(!s.contains(year)){
                    lDate.remove(s);
                }
            }
            return lDate;
        } catch (Exception e) {
            return null;
        }
    }


    /***
     * 15.获取当前时间N年之前或者之后的时间
     * @param n	-n表示n年前,n表n年后
     * @return
     */
    public static String getNowYearAgoTimeminus(int n){
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.YEAR, n);// n年时间
        Date beforeD = beforeTime.getTime();
        String before = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(beforeD);  // n分钟时间
        return before;
    }

    /***
     * 16.获取N天前的时间
     * args   yyyy-MM-dd HH:mm
     * @throws Exception
     */
    public static String getAgoDayTime(int N) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -N);
        date = calendar.getTime();
        System.out.println(sdf.format(date));
        return sdf.format(date);
    }

    /***
     * 17.日期转化为时间戳
     * args
     * @throws Exception
     */
    public static Long dateChangeDateMilli(Date dt) {

        return 1L;
    }


    /***
     * 18.获取当前的星期数
     * args
     * @throws Exception
     */
    @SuppressWarnings("static-access")
    public static int getNowWeekDay() {
        Calendar calendar;
        calendar = Calendar.getInstance();
        System.out.println(calendar);
        String week;
        week = calendar.get(calendar.DAY_OF_WEEK) - 1 + "";
        if ("0".equals(week)) {
            week = "7";
        }
        return new Integer(week);
    }

    /***
     * 19.获取当前系统时间的年月,格式:202008
     * args
     * @throws Exception
     */
    public static String getNowYearYue() {
        return DateUtil.format(getNowDateToDate(), "yyyyMM");
    }

    /***
     * 20.获取当前时间的N天之后、之前的时间
     * @param N	正数表示之后,负数表示之前
     * @return
     */
    public static String getNowDateBeforeOrAfter(int N) {
        Calendar calendar2 = Calendar.getInstance();
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        calendar2.add(Calendar.DATE, N);
        String three_days_after = sdf2.format(calendar2.getTime());
        return three_days_after;
    }

    /**
     * 21.判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致
     * @param nowTime 当前时间
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return  true 表示在这个时间段,false 表示没有
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);
        Calendar end = Calendar.getInstance();
        end.setTime(endTime);
        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    /***
     * 22.获取N秒钟之后的时间,正数表示之后,负数表示之前
     * @param thisDate	当前时间
     * @param n		你秒时候的时间  yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String getNowTimeAfter(Date thisDate, int n) {
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date newDate = addSeconds(thisDate,n);
        return dateFormat.format(newDate);
    }

    public static Date addSeconds(Date date,int seconds) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.SECOND,seconds);
        return calendar.getTime();
    }


    /***
     * 23.计算两个时间相差的毫秒
     * args
     * @throws Exception
     */
    public static double getTwoTimeCha(String beginTime) {
        Calendar nowDate=Calendar.getInstance();
        Calendar oldDate=Calendar.getInstance();
        nowDate.setTime(new Date());//设置为当前系统时间
        oldDate.setTime(DateHelper.getStrDateToDate(beginTime));//设置为想要比较的日期
        Long timeNow=nowDate.getTimeInMillis();
        Long timeOld=oldDate.getTimeInMillis();
        Long time = (timeOld-timeNow);//相差毫秒数
        return time;
    }

    /***
     * 24.时间转换为时间戳
     */
    public static String dataToStamp(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

    /***
     * 25.时间戳计算相差的秒数
     */
    public static int dateDifferSecondsI(long time1,long time2) throws Exception {
        long x=time1-time2;
        x=Math.abs(x);
        int z=(int) (x/1000);
        if(z>=0) {
            return z;
        }else {
            return 0;
        }

    }

    /***
     * 26.计算两个时间的相差秒数
     */
    public static int calLastedTime(String startDate, String endDate) {
        long a=getStrDateToDate(endDate).getTime();
        long b=getStrDateToDate(startDate).getTime();
        int c=(int) ((a-b)/1000);
        return c;
    }

    /***
     * 27.获取当前分钟数
     */
    public static int getMinute() {
        Calendar cal = Calendar.getInstance();
        int minute = cal.get(Calendar.MINUTE);
        return minute;
    }

    /***
     * 28.获取当前小时数
     */
    public static int getHour() {
        Calendar cal = Calendar.getInstance();
        int hour=cal.get(Calendar.HOUR_OF_DAY);
        return hour;
    }

    /***
     * 29.判断当前时间是否在两个时间区间内
     * nowTime	当前时间,格式09:00:00
     * startTime 开始时间,格式09:00:00
     * endTime	结束时间,格式09:00:00
     * @return
     */
    public static boolean checkWorkTimeOnOut(String nowTimes, String startTimes, String endTimes) {
        String format = "HH:mm:ss";
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
        String now = sf.format(new Date());
        Date nowTime;
        try {
            nowTime = new SimpleDateFormat(format).parse(now);
            Date startTime = new SimpleDateFormat(format).parse(startTimes);
            Date endTime = new SimpleDateFormat(format).parse(endTimes);
            if (nowTime.getTime() == startTime.getTime() || nowTime.getTime() == endTime.getTime()) {
                return true;
            }
            Calendar date = Calendar.getInstance();
            date.setTime(nowTime);
            Calendar begin = Calendar.getInstance();
            begin.setTime(startTime);
            Calendar end = Calendar.getInstance();
            end.setTime(endTime);
            if (date.after(begin) && date.before(end)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }



    public static void main(String[] args) throws Exception {
        

    }


}