1. 程式人生 > >java中對Date日期一些處理

java中對Date日期一些處理

package com.hx.cyb.common.util;

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


/**
 * 
 * @description:日期工具類   
 * @fileName:DateUtil.java 
 * @createTime:2015年3月18日 下午2:15:53  
 * @version 1.0.0  
 *
 */
public class DateUtil {
private static Calendar cal = Calendar.getInstance();
	
	/**
	 * 獲取兩個時間相差的小時數 
	 * @param start
	 * @param end
	 * @return
	 */
	public static double getDiffHour(Date start ,Date end) {
		double diff = (end.getTime() - start.getTime())/1000/60/60;
		return diff;
	}
	
	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	public static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
	public static SimpleDateFormat sdf3 = new SimpleDateFormat("yyMMdd");
	public static SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static SimpleDateFormat sdf5 = new SimpleDateFormat("yyyyMMddHHmmss");
    public static SimpleDateFormat sdf6 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
    public static SimpleDateFormat sdf7 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
    public static SimpleDateFormat sdf8 = new SimpleDateFormat("yyyy年MM月dd日");
    public static SimpleDateFormat sdf9 = new SimpleDateFormat("MM.dd");
    public static SimpleDateFormat sdf10 = new SimpleDateFormat("yyMMddHHmmss");
    
	public static Date toDataYYYYMMDD(String str) {
		try {
			return sdf.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static Date toDataYYYYMMDDHHmmss(String str) {
		try {
			return sdf4.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String formatDataYYYYMMDD(Date date) {
		return sdf2.format(date);
	}
	public static String formatDataYYMMDD(Date date) {
		return sdf3.format(date);
	}
	public static String formatDataYYMMDDHHMMSS(Date date) {
		return sdf5.format(date);
	}
	public static String formatDatayyMMDDHHMMSS(Date date) {
		return sdf10.format(date);
	}
	
	public static String formatDataYYYYMMDDLine(Date date) {
		return sdf.format(date);
	}
	public static String formatDataToDatetime(Date date){
		return sdf4.format(date);
	}
	/**
	 * 獲取當前日期month個月後的日期 
	 * @param date
	 * @param month
	 * @return
	 */
	public static Date getAddMonthDate(Date date ,int month) {
		Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, month);
        return calendar.getTime();
	}
	 
	/**
	 * 格式化日期x年x月x日 xx:xx
	 * @param date
	 * @return
	 */
	public static String getZHDate(Date date) {
        String zhDate = sdf6.format(date);
        return zhDate;
	}
	public static String getZHShortDate(Date date){
		String zhShortDate = sdf8.format(date);
		return zhShortDate;
	}
	/**
     * 按天借款的方式 返款時間的計算
     * @param releaseTime 放款時間
     * @param termCount 借款天數
     * @return 還款日期
     */
    public static Date getDayRepayDate(Date releaseTime,int termCount) {
    	Calendar calendar = Calendar.getInstance();
        calendar.setTime(releaseTime);
        calendar.add(Calendar.DATE, termCount);
        return calendar.getTime();
    }
	/**
	 * 獲取某天之前或者之後自然日 返回格式   :yyyy-MM-dd
	 * @param releaseTime
	 * @param termCount   負數則為之前    正數則為之後
	 * @return
	 */
	public static String getNatureDay(Date releaseTime,int termCount){
		Date date = getDayRepayDate(releaseTime,termCount);
		return sdf.format(date);
	}
	/**
	 *  獲取某天之前或者之後自然日 返回格式   :yyyy-MM-dd HH:mm:ss
	 * @param releaseTime
	 * @param termCount 負數則為之前    正數則為之後
	 * @return String
	 * @Description:  
	 * @date 2015年3月11日 下午12:47:18 
	 * @version V1.0
	 */
	public static Date getNatureDay(String releaseTime,int termCount){
        Calendar calendar = Calendar.getInstance() ;  
        try {  
            calendar.setTime(sdf4.parse(releaseTime)) ;  
        } catch (java.text.ParseException e) {  
            e.printStackTrace();  
        }  
        calendar.add(calendar.DATE,termCount) ;  
        return calendar.getTime() ;  
	}
	 
	/**
	 * 獲取某天之前或者之後的幾個月自然日 返回格式   :yyyy-MM-dd
	 * @param date
	 * @param month   負數則為之前    正數則為之後
	 * @return
	 */
	public static String getNatureMonth(Date date ,int month){
		Date dateCal = getAddMonthDate(date,month);
		return sdf.format(dateCal);
	}
	
	/**
	 * 判斷兩個其實是否為同一天
	 * @param date
	 * @param date2
	 * @return
	 */
	public static boolean isSameDay(Date date, Date date2){
		if(date == null || date2 == null) return false;
		return differDays(date, date2) == 0?true:false;
	}
	
	/**
	 *  判斷引數日期是否為當天
	 * @param date
	 * @param todayDate
	 * @return
	 */
	public static boolean isToday(Date date){
		if(date == null) return false;
		return differDays(date, new Date()) == 0? true: false;
	}
	
	
	/**
	 * 判斷給定日期與當天相差的天數     給定的日期為以後的日期則為負數
	 * @param date
	 * @param todayDate
	 * @return
	 */
	public static int differDays(Date date, Date baseDate){
		if(date == null) return -1;
		cal.setTime(date);
		Calendar today = Calendar.getInstance();
		today.setTime(baseDate);
		int differYearDay = today.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR);
		if(today.get(Calendar.YEAR) > cal.get(Calendar.YEAR)){
			int templYear = cal.get(Calendar.YEAR);
			differYearDay = 0;
			while(templYear != today.get(Calendar.YEAR)){
				cal.set(Calendar.YEAR, templYear ++);
				differYearDay += cal.getActualMaximum(Calendar.DAY_OF_YEAR);
			}
			differYearDay = differYearDay + today.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR);
		}else if(today.get(Calendar.YEAR) < cal.get(Calendar.YEAR)){
			int templYear = cal.get(Calendar.YEAR);
			differYearDay = cal.get(Calendar.DAY_OF_YEAR);
			templYear --;
			while(templYear != today.get(Calendar.YEAR)){
				cal.set(Calendar.YEAR, templYear --);
				differYearDay += cal.getActualMaximum(Calendar.DAY_OF_YEAR);
			}
			differYearDay += today.getActualMaximum(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR);
			differYearDay = -differYearDay;
		}
		return differYearDay;
	}
	
	/**
	 * 獲取給定日期與當前日期相差天數
	 * @function:  
	 * @param date
	 * @return int   
	 * @exception 
	 * @author:HX1401122   
	 * @since  1.0.0
	 */
	public static int differDays(Date date){
		Date baseDate = new Date();
		return differDays(baseDate,date);
	}
	
	/**
	 * 
	 * @function:計算兩個日期相差天數  
	 * @param startDate 開始時間
	 * @param endDate 結束時間
	 * @return int   
	 * @exception 
	 * @since  1.0.0
	 */
	public static int differDaysWithoutRigor(Date startDate, Date endDate){
		
		try
		{
			return daysBetween(startDate,endDate);
		}
		catch (ParseException e)
		{
			e.printStackTrace();  
		}
		return 0;
	}
	
	
	public static Date nextYear(int hav, Date date){
		return next(Calendar.YEAR, hav, date);
	}
	
	public static Date nextMonth(int hav, Date date){
		return next(Calendar.MONTH, hav, date);
	}
	
	public static Date nextDay(int hav, Date date){
		return next(Calendar.DAY_OF_MONTH, hav, date);
	}
	
	public static Date next(int dateType, int hav, Date date){
		cal.setTime(date);
		cal.add(dateType, hav);
		return cal.getTime();
	}
	
	public static Date nextDayUpdateTime(int hav, Date date){
		Calendar calOrg = Calendar.getInstance();
		calOrg.setTime(date);
		Calendar newCal = Calendar.getInstance();
		newCal.set(Calendar.YEAR, calOrg.get(Calendar.YEAR));
		newCal.set(Calendar.MONTH, calOrg.get(Calendar.MONTH));
		newCal.set(Calendar.DAY_OF_MONTH, calOrg.get(Calendar.DAY_OF_MONTH));
		newCal.add(Calendar.DAY_OF_MONTH, hav);
		return newCal.getTime();
	}
	
	public static String nextDayByHour(int hav, Date date){
    	SimpleDateFormat dft=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
    	Calendar   dar=Calendar.getInstance();     
    	dar.setTime(date);     
    	dar.add(java.util.Calendar.HOUR_OF_DAY, hav);     
        return dft.format(dar.getTime());
	}
	/**
	 * 比較給的時間與現在的時間前後順序   true:之後的時間、 false:之前的時間
	 * @param hour
	 * @param minute
	 * @return
	 */
	public static boolean afterTime(int hour, int minute){
		int nowHour = cal.get(Calendar.HOUR_OF_DAY);
		int nowMinute = cal.get(Calendar.MINUTE) + 5;
		
		
		if(nowHour < hour) return true;
		if(nowHour > hour) return false;
		if(nowHour == hour && nowMinute <= minute) return false;
		return true;
	}
	/**
	 * 
	 * description: 將日期轉字串
	 * 
	 * @param date 日期
	 * @param format 日期格式
	 * @return String 字串
	 * @since 1.0.0
	 */
	public static String dateToString(Date date, String format)
	{
		SimpleDateFormat df = new SimpleDateFormat(format);
		return df.format(date);
	}
	/**
	 * 
	 * @function:字串轉日期  
	 * @param str 字串
	 * @param formatt 日期格式,如:yyyy-MM-dd
	 * @return Date   
	 * @exception 
	 * @since  1.0.0
	 */
	public static Date StringToDate(String str,String formatt)
	{
		Date date = null;
		try {
			  if(!StringUtils.isEmpty(str))
			  {
		        SimpleDateFormat format = new SimpleDateFormat(formatt);		   
		   
		         date = format.parse(str);
			   }
		   } catch (ParseException e) {
		    e.printStackTrace();
		   }
		   return date;
	}
	/**  
     * 計算兩個日期之間相差的天數  
     * @param smdate 較小的時間 
     * @param bdate  較大的時間 
     * @return 相差天數 
     * @throws ParseException  
     */    
    public static int daysBetween(Date smdate,Date bdate) throws ParseException    
    {    
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        smdate=sdf.parse(sdf.format(smdate));  
        bdate=sdf.parse(sdf.format(bdate));  
        Calendar cal = Calendar.getInstance();    
        cal.setTime(smdate);    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(bdate);    
        long time2 = cal.getTimeInMillis();         
        long between_days=(time2-time1)/(1000*3600*24);  
            
       return Integer.parseInt(String.valueOf(between_days));           
    }    
      
    /**
     * 
     * @function:字串的日期格式的計算  
     * @param smdate
     * @param bdate
     * @return int
     * @throws ParseException    
     * @exception 
     * @since  1.0.0
     */
    public static int daysBetween(String smdate,String bdate) throws ParseException{  
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        Calendar cal = Calendar.getInstance();    
        cal.setTime(sdf.parse(smdate));    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(sdf.parse(bdate));    
        long time2 = cal.getTimeInMillis();         
        long between_days=(time2-time1)/(1000*3600*24);  
            
       return Integer.parseInt(String.valueOf(between_days));     
    }  
    
    /**
     * @function: unix時間戳轉換為日期  
     * @param timeStamp
     * @return
     * @throws ParseException Date   
     * @exception 
     * @author:duyubo   
     * @since  1.0.0
     */
    public static Date timeStampToDate(Long unixTimeStamp) throws ParseException{
    	if(unixTimeStamp != null){
    		SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
    		return format.parse(format.format(unixTimeStamp*1000));
    	}
    	return null;
    }
    
    /**
     * @function:秒數轉為時間格式  
     * @param time
     * @return String   
     * @exception 
     * @author:duyubo   
     * @since  1.0.0
     */
    public static String secToTime(int time) {
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time > 0){
        	minute = time / 60;
        	if (minute < 1){
        		timeStr = time +"秒";
        	} else if (minute < 60) {
        		second = time % 60;
        		timeStr = minute + "分" + unitFormat(second) +"秒";
        	} else {
        		hour = minute / 60;
        		if (hour > 99)
        			return "99小時59分59秒";
        		minute = minute % 60;
        		second = time - hour * 3600 - minute * 60;
        		timeStr = hour + "小時" + unitFormat(minute) + "分" + unitFormat(second) +"秒";
        	}
        }
        return timeStr;
    }

    public static String unitFormat(int i) {
        String retStr = null;
        if (i >= 0 && i < 10)
            retStr = "0" + Integer.toString(i);
        else
            retStr = "" + i;
        return retStr;
    }
    /**
     * 計算兩個時間的秒差
     * @param start
     * @param end
     * @return int
     * @Description:  
     * @date 2015年3月14日 下午10:42:06 
     * @version V1.0
     */
    public static int differSecond(Date start ,Date end){
    	return (int)((end.getTime()-start.getTime())/1000);
    }

	
}