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 _dayMins = 24*60;
    int _hourMins = 60;
    if(surplusMins >= _dayMins){//時間相隔大於1天
    surplusTime = surplusMins/_dayMins+"天"+surplusMins%_dayMins/_hourMins+"小時";
    } else if(surplusMins <= 1 && surplusMins > 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 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;
    }

創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()