首页 > 代码库 > 根据时间戳计算两个时间差

根据时间戳计算两个时间差

/**
     * 两个时间相差距离多少天多少小时多少分多少秒  <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 + "秒";
        }
    }

/**
     * 两个时间相差距离多少天多少小时多少分多少秒 <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; 
    }