Java計算兩時間相差日期,返回HH:mm 小時分鍾格式


原理其實很簡單,就是根據兩個日期相差的天數,小時數,分鍾數,秒數計算之后轉換成HH:mm格式,廢話不多說,直接上代碼

public static String timeSubtraction(String time1, String time2) throws ParseException {
/**

*@description time2 是大的時間

*@param [time1, time2]

*@return java.lang.String

*/
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小時制
long newTime1 = simpleDateFormat.parse(time2).getTime();
long newTime2 = simpleDateFormat.parse(time1).getTime();
Long result = newTime1 - newTime2; //獲取兩時間相差的毫秒數
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long hour = result % nd / nh; //獲取相差的小時數
long min = result % nd % nh / nm; //獲取相差的分鍾數
long day = result / nd;

SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");//初始化Formatter的轉換格式。
long hMiles = hour * 3600000; //小時數轉換成毫秒
long mMiles = min * 60000; //分鍾數轉換成毫秒
long resulMiles = (hMiles + mMiles);

   //下面這段很重要 ,計算之后設置時區,不然會差幾小時
formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
String resultFormat = formatter.format(resulMiles);
  //我這段是在一天內計算的 如果大於一天 就把下面的 day*24加到小時上就可以了
return resultFormat + "," + day;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM