Java常用工具類之DateUtils

Java常用工具類之DateUtils

  1. 需要引入的pom座標
		<!-- GENERAL UTILS begin -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.2</version>
        </dependency>
  1. DateUtils的編寫
		package com.xinchacha.security.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

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

/**
 * @ClassName DateUtils
 * @Description TODO
 * @Author yiGeXinDong
 * @Date 2020/5/11 9:53
 * @Version 1.0
 **/
public class DateUtils   {
    public final static int FORMAT_DEFAULT = 0; // 默認格式

    /** 日時字符串格式:長格式(如:年份用4位表示) */
    public final static int FORMAT_LONG = 1; // 長格式(如:年份用4位表示)

    /** 日時字符串格式:短格式(如:年份用2位表示) */
    public final static int FORMAT_SHORT = 2; // 短格式(如:年份用2位表示)

    /** 默認日期字符串格式 "yyyy-MM-dd" */
    public final static String DATE_DEFAULT = "yyyy-MM-dd";
    /** 日期字符串格式 "yyyy" */
    private final static String DATE_YYYY="yyyy";
    /** 日期字符串格式 "mm" */
    private final static String DATE_MM="mm";
    /** 日期字符串格式 "dd" */
    private final static String DATE_DD="dd";
    /** 日期字符串格式 "yyyyMM" */
    public final static String DATE_YYYYMM = "yyyyMM";

    /** 日期字符串格式 "yyyyMMdd" */
    public final static String DATE_YYYYMMDD = "yyyyMMdd";

    /** 日期字符串格式 "yyyy-MM" */
    public final static String DATE_YYYY_MM = "yyyy-MM";

    /** 日期字符串格式 "yyyy-MM-dd" */
    public final static String DATE_YYYY_MM_DD = "yyyy-MM-dd";

    /** 默認日時字符串格式 "yyyy-MM-dd HH:mm:ss" */
    public final static String DATETIME_DEFAULT = "yyyy-MM-dd HH:mm:ss";

    /** 日時字符串格式 "yyyy-MM-dd HH:mm" */
    public final static String DATETIME_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";

    /** 日時字符串格式 "yyyy-MM-dd HH:mm:ss" */
    public final static String DATETIME_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    /** 日時字符串格式 "yyyy-MM-dd HH:mm:ss.SSS" */
    public final static String DATETIME_YYYY_MM_DD_HH_MM_SS_SSS = "yyyy-MM-dd HH:mm:ss.SSS";

    /** 默認時間字符串格式 "HH:mm:ss" */
    public final static String TIME_DEFAULT = "HH:mm:ss";

    /** 默認時間字符串格式 "HH:mm" */
    public final static String TIME_HH_MM = "HH:mm";

    /** 默認時間字符串格式 "HH:mm:ss" */
    public final static String TIME_HH_MM_SS = "HH:mm:ss";
    public static final long YEAR_NUMBER=365;
    /** 分 */
    public static final long MINUTE_TTL = 60 * 1000l;
    /** 時 */
    public static final long HOURS_TTL = 60 * 60 * 1000l;
    /** 半天 */
    public static final long HALF_DAY_TTL = 12 * 60 * 60 * 1000l;
    /** 天 */
    public static final long DAY_TTL = 24 * 60 * 60 * 1000l;
    /** 月 */
    public static final long MONTH_TTL = 30 * 24 * 60 * 60 * 1000l;



    /**
     * TODO 計算兩個時間差值
     * @param startDate,endDate
     * @Author XuWenXiao
     * @return int(兩個時間相差的天數)
     * @throws ParseException
     */
    public static int daysBetween(Date startDate, Date endDate) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        long sTime = calendar.getTimeInMillis();
        calendar.setTime(endDate);
        long endTime = calendar.getTimeInMillis();
        long between_days=(endTime-sTime)/DAY_TTL;
        return Integer.parseInt(String.valueOf(between_days));
    }
    /**
     * TODO 獲取當前系統時間
     * @Author XuWenXiao
     * @return Date
     */
    public static Date getNewDate(){
        SimpleDateFormat df = new SimpleDateFormat(DATETIME_YYYY_MM_DD_HH_MM_SS);//設置日期格式
        Date newDate=null;
        try {
            newDate=df.parse(df.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return newDate;
    }
    /**
     * 得到日期字符串 默認格式(yyyy-MM-dd) pattern可以爲:"yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String formatDate(Date date, Object... pattern) {
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {
            formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = DateFormatUtils.format(date, DATE_YYYY_MM_DD);
        }
        return formatDate;
    }
    /**
     * 得到當前年份字符串 格式(yyyy)
     */
    public static String getYear() {
        return formatDate(new Date(), DATE_YYYY);
    }
    /**
     * 得到當前月份字符串 格式(MM)
     */
    public static String getMonth() {
        return formatDate(new Date(), DATE_MM);
    }
    /**
     * 得到當天字符串 格式(dd)
     */
    public static String getDay() {
        return formatDate(new Date(), DATE_DD);
    }
    /**
     * 獲取當前時間的字符串形式(例如;"201806291135")
     * @return 年月日時分
     */
    public static String getDateToString(){
        Calendar c = Calendar.getInstance();
        return getYear()+getMonth()+getDay()+c.get(Calendar.HOUR_OF_DAY)+c.get(Calendar.MINUTE);
    }
    /**
     * 獲取過去的年數
     * @param date
     * @return
     */
    public static Long pastYear(Date date) {
        return date==null?null:pastDays(date)/YEAR_NUMBER;
    }

    /**
     * 獲取過去的天數
     * @param date
     * @return
     */
    public static long pastDays(Date date) {
        long t = new Date().getTime()-date.getTime();
        return t/DAY_TTL;
    }

    /**
     * 獲取過去的小時
     * @param date
     * @return
     */
    public static long pastHour(Date date) {
        long t = new Date().getTime()-date.getTime();
        return t/HOURS_TTL;
    }

    /**
     * 獲取過去的分鐘
     * @param date
     * @return
     */
    public static long pastMinutes(Date date) {
        long t = new Date().getTime()-date.getTime();
        return t/MINUTE_TTL;
    }
    /**
     * 獲取兩個日期之間的天數
     *
     * @param before
     * @param after
     * @return
     */
    public static double getDistanceOfTwoDate(Date before, Date after) {
        long beforeTime = before.getTime();
        long afterTime = after.getTime();
        return (afterTime - beforeTime) /DAY_TTL;
    }
    /**
     * 根據身份證計算出身日期
     *
     */
    /**
     * 通過身份證號碼獲取出生日期、性別、年齡
     * @param certificateNo
     * @return 返回的出生日期格式:1990-01-01   性別格式:2-女,1-男
     */
    public static Map<String, String> getBirAgeSex(String certificateNo) {
        System.out.println(certificateNo);
        String birthday = "";
        String age = "";
        String sexCode = "";
        int year = Calendar.getInstance().get(Calendar.YEAR);
        char[] number = certificateNo.toCharArray();
        boolean flag = true;
        if (number.length == 15) {
            for (int x = 0; x < number.length; x++) {
                if (!flag) return new HashMap<String, String>();
                flag = Character.isDigit(number[x]);
            }
        } else if (number.length == 18) {
            for (int x = 0; x < number.length - 1; x++) {
                if (!flag) return new HashMap<String, String>();
                flag = Character.isDigit(number[x]);
            }
        }
        if (flag && certificateNo.length() == 15) {
            birthday = "19" + certificateNo.substring(6, 8) + "-"
                    + certificateNo.substring(8, 10) + "-"
                    + certificateNo.substring(10, 12);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 3, certificateNo.length())) % 2 == 0 ? "2" : "1";
            age = (year - Integer.parseInt("19" + certificateNo.substring(6, 8))) + "";
        } else {
            birthday = certificateNo.substring(6, 10) + "-"
                    + certificateNo.substring(10, 12) + "-"
                    + certificateNo.substring(12, 14);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1)) % 2 == 0 ? "2" : "1";
            age = (year - Integer.parseInt(certificateNo.substring(6, 10))) + "";
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("birthday", birthday);
        map.put("age", age);
        map.put("sexCode", sexCode);
        return map;
    }
    /**
     * 根據身份證的號碼算出當前身份證持有者的年齡 18位身份證
     * @author 黃濤
     * @return
     * @throws Exception
     */
    public static int getCarAge(String birthday){
        String year = birthday.substring(0, 4);//得到年份
        String yue = birthday.substring(4, 6);//得到月份
        //String day = birthday.substring(6, 8);//
        Date date = new Date();// 得到當前的系統時間
        SimpleDateFormat format = new SimpleDateFormat(DATE_YYYY_MM_DD);
        String fYear = format.format(date).substring(0, 4);// 當前年份
        String fYue = format.format(date).substring(5, 7);// 月份
        // String fday=format.format(date).substring(8,10);
        int age = 0;
        if (Integer.parseInt(yue) <= Integer.parseInt(fYue)) { // 當前月份大於用戶出身的月份表示已過生
            age = Integer.parseInt(fYear) - Integer.parseInt(year) + 1;
        } else {// 當前用戶還沒過生
            age = Integer.parseInt(fYear) - Integer.parseInt(year);
        }
        return age;
    }
    /**
     *
     * 根據身份證獲取性別
     */
    public static String getCarSex(String CardCode){
        String sex;
        if (Integer.parseInt(CardCode.substring(16).substring(0, 1)) % 2 == 0) {// 判斷性別
            sex = "2";
        } else {
            sex = "1";
        }
        return sex;
    }



    /**
     * 根據傳入的日曆型日期,計算出執行的時間值(精確版)
     * @param beginTime
     * @param endTime
     * @return
     */
    public static String countExecTimeToString_exact(Calendar beginTime,Calendar endTime)
    {//計算兩個日期類型之間的差值(單位:毫秒)
        Long timeDispersion = endTime.getTimeInMillis() - beginTime.getTimeInMillis();
        String tmpMsg = "耗時: ";//拼寫輸出的字符串
        int timeNum = 0;//記錄時間的數值(幾小時、幾分、幾秒)
        if(timeDispersion >= (HOURS_TTL))//判斷是否足夠一小時
        {//若足夠則計算有幾小時
            timeNum = (int) (timeDispersion/HOURS_TTL);
            tmpMsg += timeNum + "時";//拼寫輸出幾小時
            timeDispersion = timeDispersion - (timeNum*HOURS_TTL);//減去小時數(這樣剩下的就是分鐘數了)
        }
        if(timeDispersion >= (MINUTE_TTL))//判斷是否足夠一分鐘
        {//若足夠則計算有幾分鐘
            timeNum = (int) (timeDispersion/MINUTE_TTL);
            tmpMsg += timeNum + "分";//拼寫輸出幾分鐘
            timeDispersion = timeDispersion - (timeNum*MINUTE_TTL);//減去分鐘數(這樣就剩下秒數了)
        }
        if(timeDispersion >= 1000)//判斷是否足夠一秒
        {//若足夠則計算幾秒
            timeNum = (int) (timeDispersion/1000);
            tmpMsg +=  timeNum + "秒";//拼寫輸出秒數
            timeDispersion = timeDispersion - timeNum*1000;//減去秒數(這樣就剩下毫秒數了)
        }
        tmpMsg += timeDispersion + "毫秒";//拼寫輸出毫秒數
        return tmpMsg;

    }//重載方法,返回Long類型(毫秒)
    public static Long countExecTimeToLong_exact(Calendar beginTime,Calendar endTime)
    {//直接返回毫秒數
        return (endTime.getTimeInMillis() - beginTime.getTimeInMillis());
    }
    /**
     * 根據傳入的long類型日期,計算出執行的時間值(精確版)
     * @param beginTime
     * @param endTime
     * @return
     */
    public static String countExecTimeToString_exact(Long beginTime,Long endTime)
    {//計算兩個日期類型之間的差值(單位:毫秒)
        Long timeDispersion = endTime - beginTime;
        String tmpMsg = "耗時: ";//拼寫輸出的字符串
        int timeNum = 0;//記錄時間的數值(幾小時、幾分、幾秒)
        if(timeDispersion >= (HOURS_TTL))//判斷是否足夠一小時
        {//若足夠則計算有幾小時
            timeNum = (int) (timeDispersion/(HOURS_TTL));
            tmpMsg += timeNum + "時";//拼寫輸出幾小時
            timeDispersion = timeDispersion - (timeNum*HOURS_TTL);//減去小時數(這樣剩下的就是分鐘數了)
        }
        if(timeDispersion >= (MINUTE_TTL))//判斷是否足夠一分鐘
        {//若足夠則計算有幾分鐘
            timeNum = (int) (timeDispersion/(MINUTE_TTL));
            tmpMsg += timeNum + "分";//拼寫輸出幾分鐘
            timeDispersion = timeDispersion - (timeNum*MINUTE_TTL);//減去分鐘數(這樣就剩下秒數了)
        }
        if(timeDispersion >= 1000)//判斷是否足夠一秒
        {//若足夠則計算幾秒
            timeNum = (int) (timeDispersion/1000);
            tmpMsg +=  timeNum + "秒";//拼寫輸出秒數
            timeDispersion = timeDispersion - timeNum*1000;//減去秒數(這樣就剩下毫秒數了)
        }
        tmpMsg += timeDispersion + "毫秒";//拼寫輸出毫秒數
        return tmpMsg;

    }
    /**
     * 獲取指定年度全部月份集合<br>
     * 格式爲yyyy-MM
     * @author 王鵬
     * @version 2019年11月16日 下午4:52:55
     * @param year 年度
     * @return
     */
    public static List<String> getYearMonthByYear(String year) {
        List<String> monthList =new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            monthList.add(year+"-"+(i<10?"0":"")+i);
        }
        return monthList;
    }

    /**
     * 獲取下個月
     * dateStr 日期
     * format 格式:yyyy-MM或yyyyMM
     * @return
     */
    public static String getPreMonth(String dateStr,String format) {
        String preMonth = "";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date;
        try {
            date = sdf.parse(dateStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(calendar.MONTH, 1);
            sdf.format(calendar.getTime());

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return preMonth;
    }
    /**
     * 獲取下個月
     * dateStr 日期
     * format 格式:yyyy-MM或yyyyMM
     * @return
     */
    public static String getPreMonthFormat(String dateStr,String format) {
        String preMonth = "";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date;
        try {
            date = sdf.parse(dateStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(calendar.MONTH, 1);
            preMonth= sdf.format(calendar.getTime());

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return preMonth;
    }
    /**
     * 日期比較
     * date1比date2大true
     */
    public static boolean dateSize(String aDate,String bDate,SimpleDateFormat format) {
        boolean str = false;
        try {
            if(StringUtils.isNotBlank(aDate)&&StringUtils.isNotBlank(bDate)) {
                Date date1 = format.parse(aDate);
                Date date2 = format.parse(bDate);
                str = date1.after(date2);
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章