Date工具类

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import com.gitee.hero.util.exception.EcsException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 时间格式化工具类
 * 
 * @author Administrator
 * 
 */
public class DateUtil extends DateUtils {
    private static final Logger logger = LoggerFactory.getLogger(DateUtil.class);

    /**
     * 缺省的日期显示格式: yyyy-MM-dd
     */
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    /**
     * 缺省的日期显示格式: yyyyMMdd
     */
    public static final String DEFAULT_DATE_SIMPLEFORMAT = "yyyyMMdd";

    /**
     * 缺省的日期时间显示格式:yyyy-MM-dd HH:mm:ss
     */
    public static final String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    
    /**
     * 缺省的日期时间显示格式:yyyy-MM-dd HH:mm:ss.SSS
     */
    public static final String DEFAULT_FULL_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";

    public static final String DATE_PATTEN = "yyyy-MM-dd";
    public static final String TIME_PATTEN = "yyyy-MM-dd HH:mm:ss";
    public static final String TIME_PATTEN_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
    public static final String TIME_PATTEN_HH_MM_SS = "HH:mm:ss";
    public static final String TIME_PATTEN_HH_MM = "HH:mm";
    public static final String TIME_PATTEN_DDMMMYY = "ddMMMyy";
    public static final int YEAR = 0;
    public static final int MONTH = 1;
    public static final int DAY = 2;
    public static final int HOUR = 3;
    public static final int MIN = 4;
    public static final int SEC = 5;


    /**
     * 比较日期大小
     * @param starDateString(yyyy-MM-dd)
     * @param endDateString(yyyy-MM-dd)
     * @return 当starDateString>endDateString返回正整数 ;当starDateString>endDateString返回负整数 ;当starDateString=endDateString返回0
     */
    public static int compareDate(String starDateString,String endDateString){
        Date startDate = changeStrToDate(starDateString, DATE_PATTEN);
        Date endDate = changeStrToDate(endDateString, DATE_PATTEN);
        if(startDate != null && endDate != null){
            return startDate.compareTo(endDate);
        }else{
            throw new EcsException("日期为空");
        }
    }
    /**
     * 日期合法性验证
     *宽松验证
     * SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
     * @param str
     * @param pattern
     * @return
     */
    public static boolean isValidDate(String str, String pattern) {
        boolean convertSuccess = true;
        // 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            // 设置lenient为false.
            // 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
            sdf.setLenient(false);
            sdf.parse(str);
        } catch (ParseException e) {
            // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }

    /**
     * 获得日期的年份
     * @param date
     * @return
     */
    public static int getYear(Date date){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 将字符串转化为Date类型,字符串格式为:yyyy-MM-dd
     * 
     * @param strTime
     * @return
     * @throws ParseException
     */
    public static Date converToshortDate(String strTime) {
        if (StringUtils.isBlank(strTime)) {
            return null;
        }

        SimpleDateFormat shortFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);

        try {
            return shortFormat.parse(strTime);
        } catch (ParseException e) {
            logger.error("日期转换错误:", e);
        }

        return null;
    }

    public static Date converToshortDate2(String strTime) {
        if (StringUtils.isBlank(strTime)) {
            return null;
        }

        SimpleDateFormat shortFormat = new SimpleDateFormat(TIME_PATTEN_DDMMMYY,Locale.ENGLISH);

        try {
            return shortFormat.parse(strTime);
        } catch (ParseException e) {
            logger.error("日期转换错误:", e);
        }

        return null;
    }

    /**
     * 将字符串转换为Date,字符串的格式必须是yyyy-MM-dd HH:mm:ss|SSS
     * 
     * @param strTime
     * @return
     */
    public static Date converToFullDate(String strTime) {
        if (StringUtils.isBlank(strTime)) {
            return null;
        }

        SimpleDateFormat fullFormat = new SimpleDateFormat(DEFAULT_FULL_DATETIME_FORMAT);

        try {
            return fullFormat.parse(strTime);
        } catch (ParseException e) {
            logger.error("日期转换错误:", e);
        }

        return null;
    }

    /**
     * 将字符串转换为Date,字符串的格式必须是yyyy-MM-dd HH:mm:ss
     * 
     * @param strTime
     * @return
     */
    public static Date converTolongDate(String strTime) {
        if (StringUtils.isBlank(strTime)) {
            return null;
        }

        SimpleDateFormat longFormat = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);

        try {
            return longFormat.parse(strTime);
        } catch (ParseException e) {
            logger.error("日期转换错误:", e);
        }

        return null;
    }

    /**
     * 将Date对象格式话成指定字符串:格式为:yyyy-MM-dd HH:mm:ss|SSS
     * 
     * @param date
     * @return
     */
    public static String converToFullString(Date date) {
        if (date == null) {
            return null;
        }

        SimpleDateFormat fullFormat = new SimpleDateFormat(DEFAULT_FULL_DATETIME_FORMAT);

        return fullFormat.format(date);
    }

    /**
     * 将Date对象格式话成指定字符串:格式为:yyyy-MM-dd HH:mm:ss
     * 
     * @param date
     * @return
     */
    public static String converToLongString(Date date) {
        if (date == null) {
            return null;
        }

        SimpleDateFormat longFormat = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);

        return longFormat.format(date);
    }

    /**
     * 将Date对象格式话成指定字符串:格式为:yyyy-MM-dd
     * 
     * @param date
     * @return
     */
    public static String converToShortString(Date date) {
        if (date == null) {
            return null;
        }

        SimpleDateFormat shortFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);

        return shortFormat.format(date);
    }

    /**
     * 获取当前时间,yyyy-MM-dd HH:mm:ss
     * 
     * @return
     */
    public static String getCurrentTime() {
        SimpleDateFormat longFormat = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
        return longFormat.format(new Date());
    }

    /**
     * 自定义时间格式化成字符串
     * 
     * @param mydate
     *            时间
     * @param ftstr
     *            格式字符串
     * @return
     * @throws Exception
     */
    public static String customtimetostr(Date mydate, String ftstr) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat(ftstr);
        return format.format(mydate);
    }

    /**
     * 得到系统当前日期时间
     * 
     * @return 当前日期时间
     */
    public static Date getNow() {
        return Calendar.getInstance().getTime();
    }

    /**
     * 得到用缺省方式格式化的当前日期 yyyy-MM-dd
     * 
     * @return 当前日期
     */
    public String getDate() {
        return getDateTime(DEFAULT_DATE_FORMAT);
    }

    /**
     * 得到用缺省方式格式化的当前日期 yyyyMMdd
     * 
     * @return 当前日期
     */
    public String getSimpleDate() {
        return getDateTime(DEFAULT_DATE_SIMPLEFORMAT);
    }

    /**
     * 得到用缺省方式格式化的当前日期及时间
     * 
     * @return 当前日期及时间
     */
    public String getDateTime() {
        return getDateTime(DEFAULT_DATETIME_FORMAT);
    }

    /**
     * 得到系统当前日期及时间,并用指定的方式格式化
     * 
     * @param pattern
     *            显示格式
     * @return 当前日期及时间
     */
    public String getDateTime(String pattern) {
        // Date datetime = Calendar.getInstance().getTime();
        Date datetime = new Date();
        return getDateTime(datetime, pattern);
    }

    /**
     * 得到用指定方式格式化的日期
     * 
     * @param date
     *            需要进行格式化的日期
     * @param pattern
     *            显示格式
     * @return 日期时间字符串
     */
    public String getDateTime(Date date, String pattern) {
        if (StringUtils.isBlank(pattern)) {
            pattern = DEFAULT_DATETIME_FORMAT;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        return dateFormat.format(date);
    }

    /**
     * 得到当前年份
     * 
     * @return 当前年份
     */
    public int getCurrentYear() {
        return Calendar.getInstance().get(Calendar.YEAR);
    }

    /**
     * 得到当前月份
     * 
     * @return 当前月份
     */
    public int getCurrentMonth() {
        // 用get得到的月份数比实际的小1,需要加上
        return Calendar.getInstance().get(Calendar.MONTH) + 1;
    }

    /**
     * 得到当前日
     * 
     * @return 当前日
     */
    public int getCurrentDay() {
        return Calendar.getInstance().get(Calendar.DATE);
    }

    /**
     * 得到当前时间的小时数
     * 
     * @return 当前时间的小时数
     */
    public int getCurrentHour() {
        return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 得到当前时间的分钟数
     * 
     * @return 当前时间的分钟数
     */
    public int getCurrentMinute() {
        return Calendar.getInstance().get(Calendar.MINUTE);
    }

    /**
     * 得到当前时间的秒数
     * 
     * @return 当前时间的秒数
     */
    public int getCurrentScend() {
        return Calendar.getInstance().get(Calendar.SECOND);
    }

    /**
     * 计算两个日期相差天数。 用第一个日期减去第二个。如果前一个日期小于后一个日期,则返回负数
     * 
     * @param one
     *            第一个日期数,作为基准
     * @param two
     *            第二个日期数,作为比较
     * @return 两个日期相差天数
     */
    public static long diffDays(Date one, Date two) {
        return (one.getTime() - two.getTime()) / (24 * 60 * 60 * 1000);
    }

    public static long diffDays(String one, String two) throws ParseException {
        Date end = converToshortDate(one);
        Date start = converToshortDate(two);
        return diffDays(end, start);
    }

    /**
     * 计算两个日期相差月份数 如果前一个日期小于后一个日期,则返回负数
     * 
     * @param one
     *            第一个日期数,作为基准
     * @param two
     *            第二个日期数,作为比较
     * @return 两个日期相差月份数
     */
    public static int diffMonths(Date one, Date two) {

        Calendar calendar = Calendar.getInstance();

        // 得到第一个日期的年分和月份数
        calendar.setTime(one);
        int yearOne = calendar.get(Calendar.YEAR);
        int monthOne = calendar.get(Calendar.MONDAY);

        // 得到第二个日期的年份和月份
        calendar.setTime(two);
        int yearTwo = calendar.get(Calendar.YEAR);
        int monthTwo = calendar.get(Calendar.MONDAY);

        return (yearOne - yearTwo) * 12 + (monthOne - monthTwo);
    }

    /**
     * 将一个字符串用给定的格式转换为日期类型。<br>
     * 注意:如果返回null,则表示解析失败
     * 
     * @param datestr
     *            需要解析的日期字符串
     * @param pattern
     *            日期字符串的格式,默认为"yyyy-MM-dd HH:mm:ss"的形式
     * @return 解析后的日期
     */
    public Date parse(String datestr, String pattern) {
        Date date = null;

        if (StringUtils.isBlank(pattern)) {
            pattern = DEFAULT_DATETIME_FORMAT;
        }

        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
            date = dateFormat.parse(datestr);
        } catch (ParseException e) {
            logger.error("日期转换错误:", e);
        }

        return date;
    }

    public Date parse(String datestr) {
        return this.parse(datestr, null);
    }

    /**
     * 将一个string格式的日期转换为另一格式的string日期
     * 
     * @param origDate
     *            待转换日期
     * @param origPattern
     *            待转换日期格式
     * @param destPattern
     *            转换后的格式
     * @param locale
     *            待转换的日期格式的地域信息
     * @return 转换后的string
     */
    public final String format(String origDate, String origPattern, Locale locale, String destPattern) {
        String result = null;
        try {
            Date date = new SimpleDateFormat(origPattern, locale).parse(origDate);
            result = new SimpleDateFormat(destPattern).format(date);
        } catch (ParseException e) {
            return origDate;
        }
        return result;
    }

    /**
     * 返回本月的第一天
     * 
     * @return 本月第一天的日期
     */
    public Date getMonthFirstDay() {
        return getMonthFirstDay(getNow());
    }

    /**
     * 返回本月的最后一天
     * 
     * @return 本月最后一天的日期
     */
    public Date getMonthLastDay() {
        return getMonthLastDay(getNow());
    }

    /**
     * 返回给定日期中的月份中的第一天
     * 
     * @param date
     *            基准日期
     * @return 该月第一天的日期
     */
    public Date getMonthFirstDay(Date date) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        // 将日期设置为给定月份的第一天
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1);

        return calendar.getTime();
    }

    /**
     * 返回给定日期中的月份中的最后一天
     * 
     * @param date
     *            基准日期
     * @return 该月最后一天的日期
     */
    public Date getMonthLastDay(Date date) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        // 将日期设置为下一月第一天
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, 1);

        // 减去1天,得到的即本月的最后一天
        calendar.add(Calendar.DATE, -1);

        return calendar.getTime();
    }

    /** * 返回一个年份是否闰年 * * @param year * @return */
    public static boolean isLeapYear(final int year) {
        if ((year & 3) != 0) {// 非4的倍数
            return false;
        }
        if (year % 25 != 0) {// 非100的倍数
            return true;
        }
        return (year & 15) == 0;// 是100的倍数并且是16的倍数(即400的倍数)
    }

    public static String getEnYearMonth(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HHmm", Locale.ENGLISH);
        return sdf.format(date);
    }

    /**
     * 两个时间相差距离N年N月N天N小时N分N秒
     * @param startDate
     * @param endDate
     * @return long[] times = { year, month, day, hour, min, sec };
     */
    public static long[] dateDiff(Date startDate, Date endDate) {
        long diff = endDate.getTime() - startDate.getTime();
        long year = diff / (365L * 24L * 60L * 60L * 1000L);
        diff = diff % (365L * 24L * 60L * 60L * 1000L);
        long month = diff / (30L * 24L * 60L * 60L * 1000L);
        diff = diff % (30L * 24L * 60L * 60L * 1000L);
        long day = diff / (24L * 60L * 60L * 1000L);
        diff = diff % (24L * 60L * 60L * 1000L);
        long hour = diff / (60L * 60L * 1000L);
        diff = diff % (60L * 60L * 1000L);
        long min = diff / (60L * 1000L);
        diff = diff % (60L * 1000L);
        long sec = diff / 1000L;
        long[] times = { year, month, day, hour, min, sec };
        return times;
    }

    /**
     * 比较日期大小
     * @param starDateString
     * @param endDateString
     * @param format
     * @return 当starDateString>endDateString返回正整数 ;当starDateString<endDateString返回负整数 ;当starDateString=endDateString返回0
     */
    public static int compareDate(String starDateString,String endDateString,String format){
        Date startDate = changeStrToDate(starDateString, format);
        Date endDate = changeStrToDate(endDateString, format);
        if(startDate != null && endDate != null){
            return startDate.compareTo(endDate);
        }else{
            throw new EcsException("日期为空");
        }
    }

    /**
     * 根据格式将字符串转换为Date
     * @param str
     * @param patten
     * @return
     */
    public static Date changeStrToDate(String str, String patten) {
        SimpleDateFormat format = new SimpleDateFormat(patten);
        Date dt = null;
        if (StringUtils.isNotBlank(str)) {
            try {
                dt = format.parse(str);
            } catch (ParseException e) {
                throw new EcsException("日期格式错误");
            }
        }else{
            throw new EcsException("日期字符串为空",new IllegalArgumentException());
        }
        return dt;
    }
    /**
     * 根据格式将字符串转换为Date
     * @param date
     * @param patten
     * @return
     */
    public static String changeDataToStr(Date date, String patten) {
        if(date == null){
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(patten);
        return format.format(date);
    }

    /**
     * 获取当前时间
     * @return
     */
    public static Date now() {
        return Calendar.getInstance().getTime();
    }

    /**
     * 计算两个日期相差(年,月,日,时,分,秒)
     * @param startDateString
     * @param endDateString
     * @param format
     * @param type (0:year,1:month,2:day,3:hour,4:min,5:sec)
     * @return
     */
    public static long dateDiff(String startDateString, String endDateString,String format, int type) {
        Date startDate = changeStrToDate(startDateString, StringUtils.isBlank(format)?TIME_PATTEN:format);
        Date endDate = changeStrToDate(endDateString, StringUtils.isBlank(format)?TIME_PATTEN:format);
        if(startDate != null && endDate != null){
            return dateDiff(startDate,endDate,type);
        }else{
            throw new EcsException("日期为空");
        }
    }

    /**
     * 计算两个日期相差(年,月,日,时,分,秒)
     * @param startDate
     * @param endDate
     * @param type (0:year,1:month,2:day,3:hour,4:min,5:sec)
     * @return
     */
    public static long dateDiff(Date startDate, Date endDate, int type) {
        long result = 0;
        long diff = endDate.getTime() - startDate.getTime();
        switch (type) {
            case YEAR://
                result = diff / (365L * 24L * 60L * 60L * 1000L);
                break;
            case MONTH://
                result = diff / (30L * 24L * 60L * 60L * 1000L);
                break;
            case DAY://
                result = diff / (24L * 60L * 60L * 1000L);
                break;
            case HOUR:// 小时
                result = diff / (60L * 60L * 1000L);
                break;
            case MIN://
                result = diff / (60L * 1000L);
                break;
            case SEC://
                result = diff / 1000L;
                break;
            default:
                break;
        }
        return result;
    }
    /**
     * 根据日期格式将时间戳转换成日期字符串
     * @param timeStamp
     * @param format
     * @return
     */
    public static String timeStamp2Date(String timeStamp,String format) {
        if(StringUtils.isBlank(timeStamp)){
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(StringUtils.isBlank(format)?TIME_PATTEN:format);
        return sdf.format(new Date(Long.valueOf(timeStamp)));
    }
    
    public static void main(String[] args) {
        converToshortDate2("10OCT19");
        System.out.println(converToshortDate2("10OCT91"));
    }
}

 

posted @ 2020-12-04 20:30  infiniteaaaaa  阅读(102)  评论(0)    收藏  举报