日期公用类


package com.epicsaas.app.attendance.util;

import com.epicsaas.framework.util.DateTimeUtils;
import org.nutz.json.Json;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 日期公用类
 */
public class DateTimeUtil {

    public static final long MILI_SENCOND_IN_AN_DAY = 24 * 60 * 60 * 1000;

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

    public static final String DEFAULT_CN_DATE_FORMAT = "yyyy年MM月dd日";

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

    public static final String DEFAULT_POIT_DATE_FORMAT = "yyyy.MM.dd";

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

    public static final String DAY_PATTERN = "MM-dd";

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

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(DEFAULT_DATE_FORMAT);

    private static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);

    private static String defaultPattern = DEFAULT_DATE_FORMAT;

    public static Date parseDatetime2Date(Date date, String formatStr) {
        return DateTimeUtils.parseStrToDate(DateTimeUtils.formateDateToStr(date, formatStr), formatStr);
    }

    /**
     * 获取指定月第一天零点
     * @return 本月第一天零点
     */
    public static Date getFirstDateOfCurrMonth(Date date) {
        Date firstDateOfCurrMonth;

        // 本月第一天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1, 0, 0, 0);

        firstDateOfCurrMonth = calendar.getTime();

        return firstDateOfCurrMonth;
    }

    /**
     * 获取本月最后一天零点
     * @return 本月最后一天零点
     */
    public static Date getLastDateOfCurrMonth(Date date) {
        Date lastDateOfCurrMonth;
        // 下个月第一天零点
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, 1, 0, 0, 0);

        lastDateOfCurrMonth = new Date(calendar.getTimeInMillis() - DateTimeUtil.MILI_SENCOND_IN_AN_DAY);

        return lastDateOfCurrMonth;
    }

    /**
     * 获取本月第一天零点
     * @return 本月第一天零点
     */
    public static Date getFirstDateOfCurrMonth() {
        Date firstDateOfCurrMonth;

        // 本月第一天
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1, 0, 0, 0);

        firstDateOfCurrMonth = calendar.getTime();

        return firstDateOfCurrMonth;
    }

    /**
     * 获取本月最后一天零点
     * @return 本月最后一天零点
     */
    public static Date getLastDateOfCurrMonth() {
        Date lastDateOfCurrMonth;

        // 下个月第一天零点
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, 1, 0, 0, 0);

        lastDateOfCurrMonth = new Date(calendar.getTimeInMillis() - DateTimeUtil.MILI_SENCOND_IN_AN_DAY);

        return lastDateOfCurrMonth;
    }

    /**
     * @Title: parseStrToDate
     * @Description: TODO(根据格式将字符串转换为日期)
     * @param @param dateStr
     * @param @param formatStr
     * @param @return    设定文件
     * @return Date    返回类型
     * @throws
     */
    public static Date parseStrToDate(String dateStr, String formatStr) {
        if (StringsUtil.isNullOrEmpty(dateStr) || StringsUtil.isNullOrEmpty(formatStr)) {
            return null;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(formatStr);
        Date date = null;
        try {
            date = dateFormat.parse(dateStr);
        } catch (ParseException ex) {
            date = null;
        }
        dateFormat = null;
        return date;
    }

    /**
     * @Title: formatDateToStr
     * @Description: TODO(日期转换为字符串)
     * @param @param date
     * @param @param formatStr
     * @param @return    设定文件
     * @return String    返回类型
     * @throws
     */
    public static String formatDateToStr(Date date, String formatStr) {
        if (date == null || StringsUtil.isNullOrEmpty(formatStr)) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        String dateStr = format.format(date);
        format = null;
        return dateStr;
    }

    /**
     * @Title: getNow
     * @Description: TODO(获取系统当前时间)
     * @param @return    设定文件
     * @return Date    返回类型
     * @throws
     */
    public static Date getNow() {
        Calendar now = Calendar.getInstance();
        return now.getTime();
    }

    /**
     *
     * 描述:把字符串的时间转换为Date对象
     * @param strDate
     * @return
     * @throws Exception
     * 最后修改时间:2015年4月14日
     * 作者:chenjie
     */
    public static Date parseDateFromString(String strDate) throws Exception {
        try {
            if (strDate == null || strDate.isEmpty()) {
                throw new RuntimeException("时间值字符串为空!");
            }
            strDate = strDate.trim();
            if (strDate.contains("/"))
                strDate = strDate.replaceAll("/", "-");
            String formatStr = "";
            //如果format为空,根据strDate来判断format格式
            //yyyy-MM-dd HH:mm:ss
            switch (strDate.length()) {
                case 5: {
                    if (strDate.substring(2, 3).equals("-")) {
                        formatStr = "MM-dd";
                    } else if (strDate.substring(2, 3).equals(":")) {
                        formatStr = "HH:mm";
                    } else {
                        throw new RuntimeException("时间格式不正确!值:" + strDate);
                    }
                }
                    break;
                case 7: {
                    formatStr = "yyyy-MM";
                }
                    break;
                case 10: {
                    formatStr = "yyyy-MM-dd";
                }
                    break;
                case 13: {
                    formatStr = "yyyy-MM-dd HH";
                }
                    break;
                case 16: {
                    formatStr = "yyyy-MM-dd HH:mm";
                }
                    break;
                case 19: {
                    formatStr = "yyyy-MM-dd HH:mm:ss";
                }
                    break;
                default:
                    throw new RuntimeException("时间格式不正确!值:" + strDate);
            }
            //如果format不为空,直接使用
            SimpleDateFormat format = new SimpleDateFormat(formatStr);
            return format.parse(strDate);
        } catch (Exception e) {
            RuntimeException ex = new RuntimeException(e.getMessage() + "-->" + "根据字符串解析时间异常!参数值:"
                    + Json.toJson(strDate));
            ex.setStackTrace(e.getStackTrace());
            throw ex;
        }
    }

    /**
     *
     * 描述:获取若干天之前或之后的时间
     * @param date
     * @param days
     * @return
     * @throws Exception
     * 最后修改时间:2015年5月7日
     * 作者:chenjie
     */
    public static Date fetchTheDateAfter(Date date, int days) throws Exception {
        try {
            Calendar cld = Calendar.getInstance();
            cld.setTime(date);
            cld.add(Calendar.DATE, days);
            return cld.getTime();
        } catch (Exception e) {
            throw new RuntimeException("获取日期的前一天失败!");
        }
    }

    /**
     * 取得当前日期 年-月-日
     *
     * @return
     */
    public static String currentDate() {
        DateFormat f = new SimpleDateFormat(defaultPattern);
        return f.format(Calendar.getInstance().getTime());
    }

    /**
     * 获取指定年月指定周的日期
     * @param year 自然年
     * @param month 自然月
     * @param weekOfMonth 每月的第几周
     * @param dayOfWeek 每周的第几天
     * @return
     */
    public static Date getAppointWeekDate(int year, int month, int weekOfMonth, int dayOfWeek) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.WEEK_OF_MONTH, weekOfMonth);
        calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);

        return calendar.getTime();
    }

    /**
     * 获取指定日期所在周是本月第几周
     * @param date 查询日期
     * @return
     */
    public static int getWeekOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        return calendar.get(Calendar.WEEK_OF_MONTH);
    }

    /**
     * 获取今天是本周的第几天
     * @param date
     * @return
     */
    public static int getDayOfWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        return calendar.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 返回指定年月周的所有日期
     * @param year
     * @param month
     * @param weekOfMonth
     * @return
     */
    public static List<Date> getAppointWeekDates(int year, int month, int weekOfMonth){
        List<Date> list = new ArrayList<>();
        list.add(getAppointWeekDate(year,month,weekOfMonth, Calendar.MONDAY));
        list.add(getAppointWeekDate(year,month,weekOfMonth, Calendar.TUESDAY));
        list.add(getAppointWeekDate(year,month,weekOfMonth, Calendar.WEDNESDAY));
        list.add(getAppointWeekDate(year,month,weekOfMonth, Calendar.THURSDAY));
        list.add(getAppointWeekDate(year,month,weekOfMonth, Calendar.FRIDAY));
        list.add(getAppointWeekDate(year,month,weekOfMonth, Calendar.SATURDAY));
        list.add(DateTimeUtils.getAdjustTime(getAppointWeekDate(year,month,weekOfMonth, Calendar.SUNDAY),7,0,0,0,0));

        return list;
    }

    public static List<String> getAppointWeekDatesFormat(int year,int month,int weekOfMonth,String formatStr){
        List<Date> dateList = getAppointWeekDates(year,month,weekOfMonth);
        List<String> list = new ArrayList<>();
        int i = 0;
        for(Date date : dateList){
            String dateStr = formatDateToStr(date,formatStr);
            switch (i) {
                case 0:
                    dateStr += "(一)";
                    break;
                case 1:
                    dateStr += "(二)";
                    break;
                case 2:
                    dateStr += "(三)";
                    break;
                case 3:
                    dateStr += "(四)";
                    break;
                case 4:
                    dateStr += "(五)";
                    break;
                case 5:
                    dateStr += "(六)";
                    break;
                case 6:
                    dateStr += "(日)";
                    break;
            }
            list.add(dateStr);
            i++;
        }

        return list;
    }

    /**
     * dateTime 转化为 date
     * @param date
     * @return
     */
    public static Date parseDatetime2Date(Date date) {
        return DateTimeUtils.parseStrToDate(DateTimeUtils.formateDateToStr(date, DateTimeUtils.FORMAT_YMD),
                DateTimeUtils.FORMAT_YMD);
    }

    public static String getMonthZH(int month) {
        String monthStr = "";
        switch (month) {
            case 1:
                monthStr = "一月";
                break;
            case 2:
                monthStr = "二月";
                break;
            case 3:
                monthStr = "三月";
                break;
            case 4:
                monthStr = "四月";
                break;
            case 5:
                monthStr = "五月";
                break;
            case 6:
                monthStr = "六月";
                break;
            case 7:
                monthStr = "七月";
                break;
            case 8:
                monthStr = "八月";
                break;
            case 9:
                monthStr = "九月";
                break;
            case 10:
                monthStr = "十月";
                break;
            case 11:
                monthStr = "十一月";
                break;
            case 12:
                monthStr = "十二月";
                break;
        }

        return monthStr;
    }

    public static String getWeekZH(int week) {
        String weekStr = "";
        switch (week) {
            case 1:
                weekStr = "第一周";
                break;
            case 2:
                weekStr = "第二周";
                break;
            case 3:
                weekStr = "第三周";
                break;
            case 4:
                weekStr = "第四周";
                break;
            case 5:
                weekStr = "第五周";
                break;
        }

        return weekStr;
    }

    public static Date getDateFromString(String dateString, String timeString) {
        String date = dateString + " " + timeString;
        return parseStrToDate(date, DATETIME_HM_PATTERN);
    }

    public static Date getStartOfYear(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.MONTH, Calendar.JANUARY);
        cal.set(Calendar.DAY_OF_MONTH, 1);

        return DateTimeUtils.setDayFirstTime(cal.getTime());
    }

    public static Date getEndOfYear(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.MONTH, Calendar.DECEMBER);
        cal.set(Calendar.DAY_OF_MONTH, 31);

        return DateTimeUtils.setDayLastTime(cal.getTime());
    }

    /**
     * 获取2个日期之间的月份
     * @param beginDate
     * @param endDate
     * @param dateList
     * @return
     */
    public static List<Date> getDifferentMonthBetweenDate(Date beginDate, Date endDate, List<Date> dateList) {
        beginDate = DateTimeUtil.parseDatetime2Date(beginDate);
        endDate = DateTimeUtil.parseDatetime2Date(endDate);
        if (DateTimeUtils.compareDate(beginDate, endDate) == 1) {
            return null;
        }
        Calendar beginCal = Calendar.getInstance();
        beginCal.setTime(beginDate);
        Calendar endCal = Calendar.getInstance();
        endCal.setTime(endDate);

        while (DateTimeUtils.compareDate(beginCal.getTime(), endCal.getTime()) < 1) {
            dateList.add(beginCal.getTime());
            beginCal.add(Calendar.MONTH, 1);
        }

        return dateList;
    }

    /**
     * 获取2个日期之间的所有天
     * @param beginDate
     * @param endDate
     * @return
     */
    public static List<Date> getDifferentDayBetweenDate(Date beginDate, Date endDate){
        List<Date> dateList = new ArrayList<>();
        //如果请假是当天
        if (compareYearAndMonthAndDay(beginDate, endDate)){
            dateList.add(beginDate);
            return dateList;
        }
        Calendar beginCal = Calendar.getInstance();
        beginCal.setTime(beginDate);
        Calendar endCal = Calendar.getInstance();
        endCal.setTime(endDate);
        //加入开始时间
        dateList.add(beginCal.getTime());
        while (!compareYearAndMonthAndDay(beginCal.getTime(), endCal.getTime())){
            beginCal.add(Calendar.DAY_OF_MONTH, 1);
            dateList.add(beginCal.getTime());
        }
        return dateList;
    }

    public static Date getTheDateBegin(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        return calendar.getTime();
    }

    public static Date getTheDateEnd(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);

        return calendar.getTime();
    }

    /**
     * 把日期增加几个月
     * @param date
     * @param num
     * @return
     */
    public static Date getAddMonth(Date date, int num) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, num);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }

    /**
     * 把日期减少几个月
     * @param date
     * @param num
     * @return
     */
    public static Date getSubMonth(Date date, int num) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -num);
        return calendar.getTime();
    }

    public static Date getYear(Date date, int length) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, -length);
        return calendar.getTime();
    }

    /**
     * 两个时间对比月和日是否相同
     * @param date
     * @param newDate
     * @return true相同
     */
    public static boolean compareMonthAndDay(Date date, Date newDate) {
        if (date == null || newDate == null) {
            return false;
        }
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(newDate);
        boolean monthEqual = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
        boolean dayEqual = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
        if (monthEqual && dayEqual) {
            return true;
        }
        return false;
    }

    /**
     * 两个时间对比年、月、日是否相同
     * @param date
     * @param newDate
     * @return true相同
     */
    public static boolean compareYearAndMonthAndDay(Date date, Date newDate) {
        if (date == null || newDate == null) {
            return false;
        }
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(newDate);
        boolean yearEqual = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
        boolean monthEqual = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
        boolean dayEqual = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
        if (monthEqual && dayEqual && yearEqual) {
            return true;
        }
        return false;
    }

    /**
     * 判断时间格式 格式必须为“YYYY-MM-dd”
     * @param sDate
     * @return
     */
    public static boolean isLegalDate(String sDate) {
        int legalLen = 10;
        if ((sDate == null) || (sDate.length() != legalLen)) {
            return false;
        }

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = formatter.parse(sDate);
            return sDate.equals(formatter.format(date));
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 利用正则表达式判断字符串是否是数字,两位小数
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        Pattern pattern = Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){2})?$");
        Matcher isNum = pattern.matcher(str);
        return isNum.matches();
    }

    /**
     * 计算时间差,结果精确到分钟
     * @param beginDate
     * @param endDate
     * @return
     */
    public static long getDifferenceOfDate(Date beginDate, Date endDate) {
        return Math.abs((endDate.getTime() - beginDate.getTime()) / DateTimeUtils.MILLIONSECOND_OF_MINUTE);
    }

    /**
     * 计算时间差,结果精确到天
     * @param beginDate
     * @param endDate
     * @return
     */
    public static long getDifferenceDate(Date beginDate, Date endDate) {
        return Math.abs((endDate.getTime() - beginDate.getTime()) / DateTimeUtils.MILLIONSECOND_OF_DAY);
    }

    /**
     * 获取是周几
     * @param date
     * @return
     */
    public static String getWeek(Date date) {
        String week = "";
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int weekday = c.get(Calendar.DAY_OF_WEEK);
        if (weekday == 1) {
            week = "周日";
        } else if (weekday == 2) {
            week = "周一";
        } else if (weekday == 3) {
            week = "周二";
        } else if (weekday == 4) {
            week = "周三";
        } else if (weekday == 5) {
            week = "周四";
        } else if (weekday == 6) {
            week = "周五";
        } else if (weekday == 7) {
            week = "周六";
        }
        return week;
    }
}

 

posted @ 2020-06-18 21:30  二次元的程序猿  阅读(136)  评论(0)    收藏  举报