1. 程式人生 > 其它 >java中實現時間差的計算

java中實現時間差的計算

java中實現時間差的計算

程式碼編寫

package com.excel.demo;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeDifference {
    /***
     * 實現時間差的計算
     * @param args
     */
    public static void main(String[] args) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date d1 = null;
            try {
                d1 = df.parse("2021-12-06 13:31:40");

            } catch (ParseException e) {
                e.printStackTrace();
            }
            Date d2 = null;
            try {
                d2 = df.parse("2021-12-05 11:30:24");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long diff = d1.getTime() - d2.getTime();
            long day_ = 1000 * 60 * 60 * 24;
            long hour_ = 1000 * 60 * 60;
            long minute_ = 1000 * 60;
            long day = diff / day_;
            long hour = (diff - (day_ * day)) / hour_;
            long minute = (diff - ((day_ * day) + (hour * hour_))) / minute_;
            long secound = ((diff - ((day_ * day) + (hour * hour_) + (minute * minute_))) / 1000);
            String res = day + "天" + hour + "時" + minute + "分" + secound + "秒";
            System.out.printf("時間差:"+res);
        }catch (Exception e) {
            e.printStackTrace();}
    }
}


執行結果

時間差:1天2時1分16秒
Process finished with exit code 0