日期工具类-持续更新

package com.zh.zohar.service.utils;


import com.zh.zohar.api.config.Constants;
import org.apache.commons.lang.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class DateUtil {

    /**
     * 日期格式
     */
    public static final String YYYYMMDD = "yyyy-MM-dd";

    /**
     * 日期时间格式
     */
    public static final String YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";

    /**
     * 按照"yyyy-MM-dd HH:mm:ss" 返回当前时间
     *
     * @return
     */
    public static String getNowTime() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(YYYYMMDDHHMMSS);
        String nowDateStr = sdf.format(d);
        return nowDateStr;
    }

    /**
     * 按照"yyyy-MM-dd" 返回当前时间
     *
     * @return
     */
    public static String getNowDate() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(YYYYMMDD);
        String nowDateStr = sdf.format(d);
        return nowDateStr;
    }

    /**
     * 日期格式化为字符串
     *
     * @param date 日期格式的日期
     * @param dateFormat  期望返回字符串的格式
     * @return
     */
    public static String dateToStr(Date date, String dateFormat) {
        String dateStr = "";
        if (date == null) {
            return dateStr;
        }
        if (StringUtils.isBlank(dateFormat)) {
            dateFormat = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        dateStr = sdf.format(date);
        return dateStr;
    }

    /**
     * 时间戳转换成日期格式字符串
     *
     * @param milliseconds 毫秒数
     * @param formatStr    日期格式
     * @return
     */
    public static String timeStamp2Date(String milliseconds, String formatStr) {
        if (StringUtils.isBlank(milliseconds)) {
            return "";
        }
        if (StringUtils.isBlank(formatStr)) {
            formatStr = "yyyy-MM-dd HH:mm:ss";
        }
        long numLong = Long.valueOf(milliseconds);
        SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
        return sdf.format(new Date(numLong));
    }

    /**
     * 时间字符串转换成日期
     *
     * @param dateStr 时间字符串
     * @return
     */
    public static Date dateStr2Date(String dateStr) {
        if (StringUtils.isBlank(dateStr)) {
            return null;
        }
        Date date;
        try {
            String formatStr = "yyyy-MM-dd HH:mm:ss";
            String formatStr2 = "yyyy-MM-dd";
            SimpleDateFormat sdf;
            if (dateStr.length() > 12) {
                sdf = new SimpleDateFormat(formatStr);
            } else {
                sdf = new SimpleDateFormat(formatStr2);
            }
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            date = null;
        }

        return date;
    }

    /**
     * 校验字符串是否匹配时间格式
     *
     * @param str
     * @return
     */
    public static boolean isValidDateForYYYY_MM_DD(String str) {
        boolean convertSuccess = true;
        // 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 设置lenient为false.
            // 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }

    /**
     * 校验开始结束时间是否包含住了指定时间
     *
     * @param start
     * @param end
     * @param date
     * @return
     */
    public static boolean checkBeginAndEndDate(String start, String end, Date date) {
        boolean convertSuccess = false;
        // 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 设置lenient为false.
            // 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
            format.setLenient(false);
            Date startDate = format.parse(start);
            Date endDate = format.parse(end);
            if (startDate.before(date) && endDate.after(date)) {
                convertSuccess = true;
            }
        } catch (ParseException e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }

    /**
     * 两个年月日时分秒之间的小时差
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long calculationDifHourBetweenTwoDate(Date startDate, Date endDate) {
        // 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
        try {

            long nh = 1000 * 60 * 60;
            // 获得两个时间的毫秒时间差异
            long diff = endDate.getTime() - startDate.getTime();
            // 计算差多少小时
            long hour = diff / nh;
            return hour;

        } catch (Exception e) {
            return 0L;
        }
    }

    /**
     * 计算两个年月日之间的月份差
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static int calculationDifMonthBetweenTwoDate(String startDate, String endDate) {

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();
            c1.setTime(sdf.parse(startDate));
            c2.setTime(sdf.parse(endDate));
            int year1 = c1.get(Calendar.YEAR);
            int year2 = c2.get(Calendar.YEAR);
            int month1 = c1.get(Calendar.MONTH);
            int month2 = c2.get(Calendar.MONTH);
            int day1 = c1.get(Calendar.DAY_OF_MONTH);
            int day2 = c2.get(Calendar.DAY_OF_MONTH);
            // 获取年的差值 
            int yearInterval = year1 - year2;
            // 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
            if (month1 < month2 || month1 == month2 && day1 < day2) {
                yearInterval--;
            }
            // 获取月数差值
            int monthInterval = (month1 + 12) - month2;
            if (day1 < day2) {
                monthInterval--;
            }
            monthInterval %= 12;
            int monthsDiff = Math.abs(yearInterval * 12 + monthInterval);
            return monthsDiff - 1;

        } catch (ParseException e) {
            return -1;
        }
    }

    /**
     * 时间前推后推指定范围,得到新时间
     *
     * @param date 原始时间
     * @param len  前后移动的范围  正数往后,负数往前
     * @param type 1:天数  2:月份  3:年份
     * @return 新时间
     */
    public static String getChangeDay(String date, int len, int type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(date));
            if (1 == type) {
                //天数
                cal.add(Calendar.DATE, len);
            } else if (2 == type) {
                //月份
                cal.add(Calendar.MONTH, len);
            } else if (3 == type) {
                //年份
                cal.add(Calendar.YEAR, len);
            }
            return sdf.format(cal.getTime());
        } catch (Exception e) {
            return date;
        }
    }

    /**
     * 时间前推后推指定范围,得到新时间
     *
     * @param date 原始时间
     * @param len  前后移动的范围  正数往后,负数往前
     * @param type 1:天数  2:月份  3:年份  4: 小时   5: 分钟
     * @return 新时间
     */
    public static String getChangeDayTime(String date, int len, int type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(date));
            if (1 == type) {
                //天数
                cal.add(Calendar.DATE, len);
            } else if (2 == type) {
                //月份
                cal.add(Calendar.MONTH, len);
            } else if (3 == type) {
                //年份
                cal.add(Calendar.YEAR, len);
            } else if (4 == type) {
                //小时
                cal.add(Calendar.HOUR, len);
            } else if (5 == type) {
                //分钟
                cal.add(Calendar.MINUTE, len);
            }
            return sdf.format(cal.getTime());
        } catch (Exception e) {
            return date;
        }
    }

    /**
     * 获取本周从周一开始,到今日的所有年月日字符串
     *
     * @return
     */
    public static List<String> getThisWeekAllDayStrList() {

        List<String> dateStrList = new ArrayList<>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int dayofweek = cal.get(Calendar.DAY_OF_WEEK) - 1;//国内外算法差异,国外第一天从周天算起,国内从周一算起
            if (1 == dayofweek) {
                //周一,只统计当天
                String dateStr = sdf.format(cal.getTime());
                dateStrList.add(dateStr);
            } else if (dayofweek > 1) {
                //周二到周五,先退到周一,再往后计算
                cal.add(Calendar.DATE, -dayofweek);
                for (int i = 0; i < dayofweek; i++) {
                    cal.add(Calendar.DATE, 1);
                    String dateStr = sdf.format(cal.getTime());
                    dateStrList.add(dateStr);
                }
            } else if (dayofweek < 1) {
                //周六周末,周六往前推5天,周末往前推6天
                cal.add(Calendar.DATE, -6);
                for (int i = 0; i < 7; i++) {
                    String dateStr = sdf.format(cal.getTime());
                    dateStrList.add(dateStr);
                    cal.add(Calendar.DATE, 1);
                }
            }
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }

        return dateStrList;

    }

    /**
     * 获取本月从一号开始,到今日的所有年月日字符串
     *
     * @return
     */
    public static List<String> getThisMonthAllDayStrList() {

        List<String> dateStrList = new ArrayList<>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            //Date date = sdf.parse("2020-05-22");
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int dayofweek = cal.get(Calendar.DAY_OF_MONTH) - 1;//从1号开始计算

            cal.add(Calendar.DATE, -dayofweek);
            for (int i = 0; i <= dayofweek; i++) {
                String dateStr = sdf.format(cal.getTime());
                dateStrList.add(dateStr);
                cal.add(Calendar.DATE, 1);
            }

        } catch (Exception e) {
            System.out.print(e.getMessage());
        }

        return dateStrList;

    }

    /**
     * 获取上周第一天(第一天是周一)
     *
     * @return
     */
    public static String getPreviousWeekFirstDayStr() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        // 将每周第一天设为星期一,默认是星期天
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.add(Calendar.DATE, -1 * 7);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return sdf.format(cal.getTime());
    }

    /**
     * 获取上周最后一天(第一天是周一)
     *
     * @return
     */
    public static String getPreviousWeekLastDayStr() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        //将每周第一天设为星期一,默认是星期天
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.add(Calendar.DATE, -1 * 7);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);

        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return sdf.format(cal.getTime());
    }

    /**
     * 获取上月第一天
     *
     * @return
     */
    public static String getPreviousMonthFirstDayStr() {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Calendar calendar = Calendar.getInstance();

        calendar.add(Calendar.MONTH, -1);

        calendar.set(Calendar.DAY_OF_MONTH, 1);

        return format.format(calendar.getTime());

    }

    /**
     * 获取上月最后一天
     *
     * @return
     */
    public static String getPreviousMonthLastDayStr() {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar calendar = Calendar.getInstance();

        int month = calendar.get(Calendar.MONTH);

        calendar.set(Calendar.MONTH, month - 1);

        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));

        return sf.format(calendar.getTime());

    }

    /**
     * 获取年月日对应星期几
     *
     * @param ymdStr
     * @return
     */
    public static String getWeekDayByDayStr(String ymdStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        Date date = null;
        int dayofweek;
        try {
            date = sdf.parse(ymdStr);
            cal.setTime(date);
            dayofweek = cal.get(Calendar.DAY_OF_WEEK) - 1;//从1号开始计算
            if (Constants.NUM_ZERO == dayofweek) {
                dayofweek = Constants.NUM_SEVEN;
            }
        } catch (ParseException e) {
            dayofweek = Constants.NUM_ZERO;
        }
        return WeekEnum.getNameByCode(String.valueOf(dayofweek));
    }

    /**
     * 枚举类-星期几
     *
     */
    enum WeekEnum {

        STATUS_1("1","星期一","星期一"),
        STATUS_2("2","星期二","星期二"),
        STATUS_3("3","星期三","星期三"),
        STATUS_4("4","星期四","星期四"),
        STATUS_5("5","星期五","星期五"),
        STATUS_6("6","星期六","星期六"),
        STATUS_7("7","星期天","星期天");

        private String code;
        private String name;
        private String desc;

        /**
         * 通过编号获取名称
         *
         * @param code
         * @return
         */
        public static String getNameByCode(String code) {
            WeekEnum[] enums = values();
            for (WeekEnum num : enums) {
                if (num.getCode().equals(code)) {
                    return num.getName();
                }
            }
            return null;
        }

        /**
         * 获取全部枚举
         *
         * @return
         */
        public static Map<String, String> getAll() {
            Map<String, String> map = new HashMap<>();
            WeekEnum[] enums = values();
            for (WeekEnum num : enums) {
                map.put(num.getCode(), num.getName());
            }
            return map;
        }

        WeekEnum(String code, String name, String desc) {
            this.code = code;
            this.name = name;
            this.desc = desc;
        }

        public String getCode() {
            return code;
        }

        private void setCode(String code) {
            this.code = code;
        }

        public String getName() {
            return name;
        }

        private void setName(String name) {
            this.name = name;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }

    }

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值