java時間格式轉換工具類

 該類主要用於格式化時間,以及計算兩時間的時間差,代碼都有註釋

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;


public class DateUtils {

  
	public static DateTimeFormatter format_ymdhms = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

	private static DateTimeFormatter format_ymdhmssss = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
	
	private static DateTimeFormatter format_ymds = DateTimeFormatter.ofPattern("yyyyMMdd");

    public static DateTimeFormatter format_ymd = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public static DateTimeFormatter format_ymdhms_string = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    public static DateTimeFormatter format_ymdhms_no_signal = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    public static SimpleDateFormat yyyyMMdd_format = new SimpleDateFormat("yyyy-MM-dd");

    public static SimpleDateFormat ymdhms_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static DateTimeFormatter format_ymd_String = DateTimeFormatter.ofPattern("yyMMdd");



    /**
     * 將日期對象格式化成指定的字符串格式
     *
     * @param date         日期對象
     * @param formatString 格式化字符串
     * @return String
     */
    public static String getDateFormatString(Date date, String formatString) {

        String dateString = "";
        SimpleDateFormat format = new SimpleDateFormat(formatString);
        if (date != null) {
            dateString = format.format(date);
        }
        return dateString;
    }

    /**
     * 字符串轉date
     * @param date 時間戳
     * @param format format
     * @return 時間
     */
    public static Date stringToDate(String date,SimpleDateFormat format){
        try {
            if(StringUtils.isBlank(date)){
                return null;
            }
            return format.parse(date);
        } catch (ParseException e) {
            logger.error(e.getMessage(),e);
        }
        return null;
    }


    /**
     * 字符串轉date
     * @param date 時間戳
     * @return 時間
     */
    public static Date stringToDateStandard (String date){
        SimpleDateFormat format = ymdhms_format;
        if(StringUtils.isNotBlank(date)){
            if(date.split("-").length==3){
                if(date.split(":").length!=3){
                    format = yyyyMMdd_format;
                }
            }else if(date.split("-").length==2){
                format = new SimpleDateFormat("yyyy-MM");
            }
            try {
                return format.parse(date);
            } catch (ParseException e) {
                logger.error(e.getMessage(),e);
            }
        }
        return null;
    }


    /**
     * 獲取當前時間
     * @return
     * @throws Exception
     */
    public static LocalDateTime getCurrentDate(){
    	LocalDateTime now = LocalDateTime.now();
    	return now;
    }
    
    /**
     * 獲取當前時間字符串,格式爲yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String getCurrentDateStr(){
    	String nowtime=getCurrentDate().format(format_ymdhms);
    	return nowtime;
    }

    public static String getCurrentDateymd(){
        String nowtime=getCurrentDate().format(format_ymdhms_string);
        return nowtime;
    }

    public static String getCurrentDateyymd(){
        String nowtime=getCurrentDate().format(format_ymd_String);
        return nowtime;
    }

    /**
     * 獲取當前時間字符串,格式爲yyyyMMdd
     * @return
     */
    public static String getCurrentDateString(){
    	String nowtime=getCurrentDate().format(format_ymds);
    	return nowtime;
    }
    

    /**
     * 獲取當前時間字符串,格式爲yyyy-MM-dd
     * @return
     */
    public static String getCurrentDateStrymd(){
        String nowtime=getCurrentDate().format(format_ymd);
        return nowtime;
    }

    public static String getCurrentDateStr_MS(){
    	String nowtime=getCurrentDate().format(format_ymdhmssss);
    	return nowtime;
    }
    
    /**
     * 獲取當前時間long值
     * @return
     */
    public static long getCurrentDataLong(){
        return new Date().getTime();
    }



    /**
     * 獲取當前時間
     * @param format
     * @return
     * @throws Exception
     */
    public static Date getCurrentDate(SimpleDateFormat format){
        String tempDate = format.format(new Date());
        try {
            return format.parse(tempDate);
        } catch (ParseException e) {
            logger.error(e.getMessage(),e);
        }
        return null;
    }

    /**
     * @param date
     * @param newFormat
     * @return
     * @throws Exception
     */
    public static Date getDate(Date date, SimpleDateFormat newFormat) {
        String tempDate = newFormat.format(date);
        try {
            return newFormat.parse(tempDate);
        } catch (ParseException e) {
            logger.error(e.getMessage(),e);
        }
        return null;
    }

    public static String format(Date date, SimpleDateFormat format) {
        if(null == date){
            return "";
        }
        return format.format(date);
    }

    /**
     * 將給定的時間秒轉換爲中文格式的時分秒
     *
     * @param second
     * @return
     */
    public static String formatSecond_ZH_HMS(Integer second) {
        String result = "0秒";
        if (null != second) {
            int hours = (int) (second / (60 * 60));
            int minutes = (int) (second / 60 - hours * 60);
            int seconds = (int) (second - minutes * 60 - hours * 60 * 60);

            String format;
            Object[] array;

            if (hours > 0) {
                format = "%1$,d時%2$,d分%3$,d秒";
                array = new Object[]{hours, minutes, seconds};
            } else if (minutes > 0) {
                format = "%1$,d分%2$,d秒";
                array = new Object[]{minutes, seconds};
            } else {
                format = "%1$,d秒";
                array = new Object[]{seconds};
            }
            result = String.format(format, array);
        }
        return result;
    }

    /**
     * 對日期進行加法操作
     *
     * @param date
     * @param days
     * @return
     */
    public static Date addDay(Date date, Integer days) {
        if (null != date) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.DATE, days);
            return cal.getTime();
        }
        return null;
    }

    /**
     * 對日期進行加法操作
     *
     * @param date
     * @param month
     * @return
     */
    public static Date addMonth(Date date, Integer month) {
        if (null != date) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.MONTH, month);
            return cal.getTime();
        }
        return null;
    }

    /**
     * 對日期進行加法操作
     * @param date
     * @param hours
     * @return
     */
    public static Date addHours(Date date, Integer hours) {
        if (null != date) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.HOUR_OF_DAY, hours);
            return cal.getTime();
        }
        return null;
    }

    /**
     * 對日期的分鐘進行加法操作
     * @param date
     * @param minutes
     * @return
     */
    public static Date addMinutes(Date date, Integer minutes) {
        if (null != date) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.MINUTE, minutes);
            return cal.getTime();
        }
        return null;
    }

    /**
     * 比較兩個日期的大小
     *
     * @param date1
     * @param date2
     * @return 日期相等,返回0;前者大,返回1;後者大,返回-1;
     */
    public static int dateCompare(Date date1, Date date2) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(date1);

        Calendar c2 = Calendar.getInstance();
        c2.setTime(date2);

        return c1.compareTo(c2);
    }

    /**
     * 判斷當前日期是否在指定日期區域內(包含起止日期) [startDate,endDate]
     * <p/>
     * [null,null] --> return 1;
     *
     * @param now
     * @param startDate
     * @param endDate
     * @return -1:超出並小於startDate;0:在範圍內;1:超出並大於endDate;
     */
    public static int validateDate(Date now, Date startDate, Date endDate) {
        if (null == startDate && null == endDate) {
            return 0;
        }
        if (null == startDate) {
            //當前時間大於endDate
            if (dateCompare(now, endDate) == 1) {
                return 1;
            } else {
                return 0;
            }
        } else {
            if (null == endDate) {
                //當前時間小於startDate
                if (dateCompare(startDate, now) == 1) {
                    return -1;
                } else {
                    return 0;
                }
            } else {
                if (dateCompare(startDate, now) == 1) {
                    return -1;
                } else if (dateCompare(now, endDate) == 1) {
                    return 1;
                } else {
                    return 0;
                }
            }
        }
    }

    /**
     * 計算兩個日期先差多少秒
     * @param pre 前一個日期
     * @param after 後一個日期
     * @return
     */
    public static long calTimeDifference(Date pre,Date after){
        return (after.getTime()-pre.getTime())/1000;
    }



    /**
     * 計算兩個時間相差的天數
     * @param stardate
     * @param enddate
     * @return
     */
    public static int getHour(Date stardate,Date enddate){
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        long diff=enddate.getTime()-stardate.getTime();

        long day = diff / nd;

        long hour = diff % nd / nh;

        long min = diff % nd % nh / nm;

        return (int)day;
    }
    
    /**
     * 結束時間與當前時間計算相差的月數
     * @param enddate
     * @return
     */
    public static int getMonthSpace(String enddate, DateTimeFormatter format) {
    	LocalDate formatted = LocalDate.parse(enddate,format);
        LocalDate today = LocalDate.now();
        Period per = Period.between(today,formatted);
        if(per.getYears() == 0 ){
        	return per.getMonths();
        }else if(per.getYears() > 0 ){
        	return (per.getYears() * 12) + per.getMonths();
        }
        
        return (per.getYears() * 12) + per.getMonths();
    }
    
    /**
     * 獲取某個時間段之前的時間點
     * @return
     */
    public static String getSomeTimeStapStr(String sign){
    	LocalDateTime beginDateTime =null;
    	if (sign.equals("day")) {//一天前時間
    		beginDateTime =LocalDateTime.now().minusDays(1L);
		}else if(sign.equals("week")){
			beginDateTime =LocalDateTime.now().minusWeeks(1L);
		}else if (sign.equals("month")) {
			beginDateTime =LocalDateTime.now().minusMonths(1L);
		}else if (sign.equals("year")) {
			beginDateTime =LocalDateTime.now().minusYears(1L);
		}
    	String beginTime=beginDateTime.format(format_ymdhms);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	try {
			long timestap = sdf.parse(beginTime).getTime();
			beginTime = timestap+"";
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	return beginTime;
    }
    
    public static String getSomeTimeDateStr(String sign){
    	String beginTime="";
    	LocalDateTime beginDateTime =null;
    	if (sign.equals("day")) {//一天前時間
    		beginDateTime =LocalDateTime.now().minusDays(1L);
		}else if(sign.equals("week")){
			beginDateTime =LocalDateTime.now().minusWeeks(1L);
		}else if (sign.equals("month")) {
			beginDateTime =LocalDateTime.now().minusMonths(1L);
		}else if (sign.equals("year")) {
			beginDateTime =LocalDateTime.now().minusYears(1L);
		}
    	if (beginDateTime!=null) {
    		beginTime = beginDateTime.format(format_ymdhms);
		}
    	return beginTime;
    }


    /**
     * 獲取失效時間點(在什麼時間失效)
     * @param minutes       有效分鐘數
     * @return
     */
    public static LocalDateTime getInvalidLocalDateTime(Long minutes){
        return LocalDateTime.now().minusMinutes(minutes);
    }


    /**
     * 獲取當前年份
     * @return
     */
    public static String getCurrentYear(){
        Calendar instance = Calendar.getInstance();
        return instance.get(Calendar.YEAR)+"";
    }


    /**
     * 獲取當前月份
     * @return
     */
    public static String getCurrentMonth(){
        Calendar instance = Calendar.getInstance();
        int month = instance.get(Calendar.MONTH);
        String result;
        if (month < 10){
            result = "0" + month;
        }else {
            result = month+"";
        }
        return result;
    }

    /** 獲取無符號的當前時間
     * @return
     */
    public static String getCurrentDateStrNoSignal(){
        return getCurrentDate().format(format_ymdhms_no_signal);
    }


    /**
     * 獲取前幾個小時的時間
     * @param hours
     * @return
     */
    public static String getNextHourDateStrNoSignal(long hours){
        return LocalDateTime.now().plusHours(hours).format(format_ymdhms_no_signal);
    }


    public static Date localDateTimeToDate(LocalDateTime localDateTime) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        return Date.from(instant);
    }

    /**
     * 小時取整
     * @param date
     * @param hour
     * @return
     */
    public static Date integralHour(Date date,Integer hour) {
        if(date==null||hour==null){
            return null;
        }
        long l = date.getTime()- 1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
        try {
            Date parse = sdf.parse(sdf.format(new Date(l)));
            return addHours(parse, hour);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 分鐘取整
     * 以十分鐘爲單位 ,去除尾端,加上 參數  46->40+minutes*10
     * @param date
     * @param minutes
     * @return
     */
    public static Date integral10Min(Date date,Integer minutes) {
        if(date==null||minutes==null){
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int i = cal.get(Calendar.MINUTE);//獲取分鐘
        if(i%10==0){
            minutes--;
        }
        minutes=minutes*10-i%10;
        long l = date.getTime()- 1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
        try {
            Date parse = sdf.parse(sdf.format(new Date(l)));
            return addMinutes(parse, minutes);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 天數取整
     * @param date
     * @param day
     * @return
     */
    public static Date integralDay(Date date,Integer day) {
        if(date==null||day==null){
            return null;
        }
        long l = date.getTime()- 1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        try {
            Date parse = sdf.parse(sdf.format(new Date(l)));
            return addDay(parse, day);
        } catch (ParseException e) {
            return null;
        }
    }





    public static void main(String[]args)throws Exception{
//        Date date= new Date();
//        Date after = new Date();
//        System.out.println(calTimeDifference(date,after));
       
    }
}

 

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