根據時間戳計算兩個時間差

/**
     * 兩個時間相差距離多少天多少小時多少分多少秒  <br>
     * 時間參數爲 Unix時間戳
     * @param str1 時間參數 1 格式:1407132214
     * @param str2 時間參數 2 格式:1407132214
     * @return String 返回值爲:xx天xx小時xx分xx秒
     */
    public static String getDistanceTime(String str1, String str2) {
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            long time1 = Long.parseLong(str1) * 1000;
            long time2 = Long.parseLong(str2) * 1000;
            long diff ;
            diff = time2 - time1;
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(hour == 0){
         return min + "分" + sec + "秒";
        }else if(day == 0){
         return hour + "小時" + min + "分" + sec + "秒";
        }else{
         return day + "天" + hour + "小時" + min + "分" + sec + "秒";
        }
    }.net

/**
     * 兩個時間相差距離多少天多少小時多少分多少秒 <br>
     * 時間參數爲 Unix時間戳
     * @param str1 時間參數 1 格式:1407132214
     * @param str2 時間參數 2 格式:1407132214
     * @return long[] 返回值爲:{天, 時, 分, 秒}
     */
    public static long[] getDistanceTimes(String str1, String str2) {
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            long time1 = Long.parseLong(str1) * 1000;
            long time2 = Long.parseLong(str2) * 1000;
            long diff ;
            diff = time2 - time1;
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
       
        long[] times = {day, hour, min, sec};
        return times; 
    }get

相關文章
相關標籤/搜索