日期工具类

ⅰ亾dé卋堺 提交于 2020-04-05 16:13:32


@Slf4j
public class DateUtils {

    public static final Calendar CALENDAR = Calendar.getInstance();

    private DateUtils() {
    }

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

    public static final String C_DATE_TIME_MIN_FORMAT = "yyyyMMdd HHmmss";

    public static final String C_DATE_TIME_FORMAT_SSS = "yyyy-MM-dd HH:mm:ss:SSS";

    public static final String C_DATE_TIME_YMD = "yyyyMMdd";

    public static final String C_DATE_TIME_HMS = "HHmmss";

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

    public static final String C_DATE_TIME_YMDHMS = "yyyyMMddHHmmss";

    public static final String C_DATE_TIME_YMDH = "yyyyMMddHH";

    public static Timestamp currentTimestamp() {
        return new Timestamp(System.currentTimeMillis());
    }

    /**
     * 获取当前日期时间
     *
     * @return
     */
    public static String getCurrentDateTime() {
        return org.apache.commons.lang3.time.DateFormatUtils.format(new Date(), C_DATE_TIME_FORMAT);
    }

    /**
     * 获取当前日期时间
     *
     * @return
     */
    public static String getCurrentDateTimeSSS() {
        return org.apache.commons.lang3.time.DateFormatUtils.format(new Date(), C_DATE_TIME_FORMAT_SSS);
    }

    /**
     * 日期字符串转日期类型
     *
     * @param dateString sample 2018-06-06 15:53:01
     * @return
     */
    public static Date pareDate(String dateString) {
        return pareDate(C_DATE_TIME_FORMAT, dateString);
    }

    public static Date pareDateStr(String dateString) {
        return pareDate(C_DATE_TIME_MIN_FORMAT, dateString);
    }

    /**
     * 日期字符串转日期类型
     *
     * @param pattern    sample yyyy-MM-dd HH:mm:ss
     * @param dateString sample 2018-06-06 15:53:01
     * @return
     */
    public static Date pareDate(String pattern, String dateString) {
        try {
            return FastDateFormat.getInstance(pattern).parse(dateString);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * yyyy-MM-dd HH:mm:ss
     * 格式化时间为默认格式
     *
     * @param date
     * @return
     */
    public static String formatDefaultTime(Date date) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    }

    /**
     * 判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致
     *
     * @param nowTime   当前时间
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    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);

        return date.after(begin) && date.before(end);
    }

    /**
     * 获取据当前时间差几天的日期
     *
     * @return
     */
    public static Date getDays(int day) {
        CALENDAR.setTime(new Date());
        CALENDAR.add(Calendar.DATE, day);
        Date d = CALENDAR.getTime();

        return d;
    }

    /**
     * 计算两个日期相差多少天
     *
     * @param start-开始时间
     * @param end-结束时间
     * @return int
     */
    public static int getDays(Date start, Date end) {
        Calendar aCalendar = Calendar.getInstance();

        aCalendar.setTime(start);

        int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);

        aCalendar.setTime(end);

        int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);

        return day2 - day1;


    }

    /**
     * 获取 YYYY-MM-DD 00:00:00
     *
     * @param day-传的参数为当月的对应日期(传1为当月1日凌晨)
     * @return date
     */
    public static Date getDaysOfMonth(int day){
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND,000);
        return calendar.getTime();
    }

    /**
     * 获取 YYYY-MM-DD 00:00:00
     *
     * @param day- 传的参数为当前日期延后几天的参数(传0为当日凌晨)
     * @return date
     */
    public static Date getDayByNum(int day) {
        CALENDAR.setTime(new Date());
        CALENDAR.add(Calendar.DATE, day);
        CALENDAR.set(CALENDAR.get(Calendar.YEAR), CALENDAR.get(Calendar.MONTH), CALENDAR.get(Calendar.DAY_OF_MONTH), 00, 00, 00);
        CALENDAR.set(Calendar.MILLISECOND,000);
        return CALENDAR.getTime();
    }


    /**
     * 获取据当前时间差几天的日期
     *
     * @return
     */
    public static Date getDays(Date date, int day) {
        CALENDAR.setTime(date);
        CALENDAR.add(Calendar.DATE, day);
        Date d = CALENDAR.getTime();

        return d;
    }

    /**
     * 获取当前时间之前的30天日期
     *
     * @return
     */
    public static Date get30Days() {
        CALENDAR.setTime(new Date());
        CALENDAR.add(Calendar.DATE, -30);
        Date d = CALENDAR.getTime();

        return d;
    }

    /**
     * 获取当前时间之前的一个月日期
     *
     * @return
     */
    public static Date getMonthDays() {
        CALENDAR.setTime(new Date());
        CALENDAR.add(Calendar.MONTH, -1);
        Date m = CALENDAR.getTime();
        return m;
    }

    /** 
     * @description 获取当前时间之前一个月的0点日期的0点。
     * @author Huang Yafeng
     * @date 2020/4/2 10:04
     * @param 
     * @return 
     */
    public static Date getBeforeMonth() {
        CALENDAR.setTime(new Date());
        CALENDAR.add(Calendar.MONTH, -1);
        CALENDAR.set(Calendar.HOUR_OF_DAY,0);
        CALENDAR.set(Calendar.MINUTE,0);
        CALENDAR.set(Calendar.SECOND,0);
        CALENDAR.set(Calendar.MILLISECOND,000);
        Date m = CALENDAR.getTime();
        return m;
    }


    /**
     * 获取当前时间之前的一年日期
     *
     * @return
     */
    public static Date getYearDays() {
        CALENDAR.setTime(new Date());
        CALENDAR.add(Calendar.YEAR, -1);
        Date y = CALENDAR.getTime();
        return y;
    }

    /**
     * 字符串转换日期格式
     *
     * @param time
     * @return
     */
    public static Date formatTime(String time, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = format.parse(time);
        } catch (Exception e) {
            log.error("日期转换失败[{}]|异常[{}]", time, e);
        }
        return date;
    }

    /**
     * 日期转换成字符串
     *
     * @param date
     * @return
     */
    public static String DateToStr(Date date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        String str = format.format(date);
        return str;
    }

    /**
     * 格式化日期类型
     *
     * @param date
     * @param pattern
     * @return
     */
    public static Date formatDate(Date date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date result = null;
        try {
            result = format.parse(DateToStr(date, pattern));
        } catch (Exception e) {
            log.error("日期转换失败[{}]|异常[{}]", date, e);
        }
        return result;
    }

    /**
     * 获取当前hour,24小时制
     */
    public static int getHour(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 获取当前时间前一小时
     *
     * @return
     */
    public static String getOneHoursAgoTime() {
        String oneHoursAgoTime = "";
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY) - 1); //把时间设置为当前时间-1小时,同理,也可以设置其他时间
        oneHoursAgoTime = new SimpleDateFormat(C_DATE_TIME_YMDH).format(cal.getTime());//获取到完整的时间
        return oneHoursAgoTime;
    }

    /**
     * 校验字符串是否符合格式
     *
     * @param dateStr
     * @param pattern
     * @return
     */
    public static boolean checkValidDate(String dateStr, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);

        try {
            // 设置lenient为false.
            // 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
            format.setLenient(false);
            format.parse(dateStr);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取当前日期
     *
     * @return
     */
    public static Date getCurrDate() {
        return new Date();
    }


    /**
     * 时间计算
     *
     * @param calendarKey
     * @param timeRange
     */
    public static Date[] DateRange(int calendarKey, int timeRange) {
        Date[] dates = new Date[2];
        Calendar createDt = Calendar.getInstance();
        createDt.add(calendarKey, -timeRange);
        if (calendarKey == Calendar.SECOND) {
            createDt.set(createDt.get(Calendar.YEAR), createDt.get(Calendar.MONTH), createDt.get(Calendar.DAY_OF_MONTH), createDt.get(Calendar.HOUR_OF_DAY), createDt.get(Calendar.MINUTE), ((createDt.get(Calendar.SECOND)) / timeRange) * timeRange);
        } else if (calendarKey == Calendar.MINUTE) {
            createDt.set(createDt.get(Calendar.YEAR), createDt.get(Calendar.MONTH), createDt.get(Calendar.DAY_OF_MONTH), createDt.get(Calendar.HOUR_OF_DAY), (createDt.get(Calendar.MINUTE) / timeRange) * timeRange, 00);
        } else if (calendarKey == Calendar.HOUR_OF_DAY) {
            createDt.set(createDt.get(Calendar.YEAR), createDt.get(Calendar.MONTH), createDt.get(Calendar.DAY_OF_MONTH), createDt.get(Calendar.HOUR_OF_DAY), 00, 00);
        } else if (calendarKey == Calendar.DAY_OF_MONTH) {
            createDt.set(createDt.get(Calendar.YEAR), createDt.get(Calendar.MONTH), createDt.get(Calendar.DAY_OF_MONTH), 00, 00, 00);
        }
        createDt.set(Calendar.MILLISECOND,000);
        Date start = createDt.getTime();
        dates[0] = start;
        createDt.add(calendarKey, timeRange);
        Date end = createDt.getTime();
        dates[1] = end;
        return dates;
    }

    public static Date[] DateRangeDay(){
        Date[] dates = new Date[2];
        Calendar createDt = Calendar.getInstance();
        createDt.set(createDt.get(Calendar.YEAR), createDt.get(Calendar.MONTH), createDt.get(Calendar.DAY_OF_MONTH), 00, 00, 00);
        createDt.set(Calendar.MILLISECOND,000);
        Date start = createDt.getTime();
        dates[0] = start;
        createDt.add(Calendar.DAY_OF_MONTH, 1);
        Date end = createDt.getTime();
        dates[1] = end;
        return dates;
    }

    public static void main(String[] args) {
        Date data = new Date();
        System.out.println(DateToStr(getDaysOfMonth(0),C_DATE_TIME_FORMAT_SSS));
    }

}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!