获取两时间间隔天、小时、分

获取两时间间隔天、小时、分
    public static void main(String[] args){
    	Date _2days = toDate("2012-11-15 18:17:20", TIME_PATTERN);
    	System.err.println(surplusUnitedTime(_2days));
    	
    	Date _1days = toDate("2012-11-14 18:17:20", TIME_PATTERN);
    	System.err.println(surplusUnitedTime(_1days));
    	
    	Date _0days = toDate("2012-11-13 18:17:20", TIME_PATTERN);
    	System.err.println(surplusUnitedTime(_0days));
    	
    	Date _days = toDate("2012-11-13 17:17:20", TIME_PATTERN);
    	System.err.println(surplusUnitedTime(_days));
    }
    
    public static String surplusUnitedTime(Date unitedEndTime){
    	String surplusTime = "";
    	Date now = new Date();
    	int surplusMins = getTimeIntervalMins(now, unitedEndTime);  
        int surplusSecond = getTimeIntervalSec(now, unitedEndTime);
    	int _dayMins = 24*60;
    	int _hourMins = 60;
    	if(surplusMins >= _dayMins){//时间相隔大于1天
    		surplusTime = surplusMins/_dayMins+"天"+surplusMins%_dayMins/_hourMins+"小时";
    	} else if(surplusMins == 0 && surplusSecond > 0){
    		surplusTime = 0+"小时"+1+"分";
    	} else if(surplusMins > 1){
    		surplusTime = surplusMins/_hourMins+"小时"+surplusMins%_hourMins+"分";
    	}
    	return surplusTime;
    }
    
    public static int getTimeIntervalMins(Date firstDate, Date lastDate) {
        if (null == firstDate || null == lastDate) {
            return -1;
        }
        
        long intervalMilli = lastDate.getTime() - firstDate.getTime();
        return (int) (intervalMilli / (60 * 1000));
    }

    public static int getTimeIntervalSec(Date firstDate, Date lastDate) {
        if (null == firstDate || null == lastDate) {
            return -1;
        }
        
        long intervalMilli = lastDate.getTime() - firstDate.getTime();
        return (int) (intervalMilli / 1000);
    }

    public static java.util.Date toDate(String sDate, String sFmt) {
        if (StringUtil.isBlank(sDate) || StringUtil.isBlank(sFmt)) {
            return null;
        }
        
        SimpleDateFormat sdfFrom = null;
        java.util.Date   dt = null;
        try {
            sdfFrom     = new SimpleDateFormat(sFmt);
            dt          = sdfFrom.parse(sDate);
        } catch (Exception ex) {
            logger.error(ex, ex);
            return null;
        } finally {
            sdfFrom = null;
        }

        return dt;
    }

你可能感兴趣的:(时间间隔)