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
上一篇:有一个容量为10L的空水桶。水桶的上面开始往里灌水,同时下面开始往出流水。第一分钟灌水的速度是1L/min,第二分钟灌水的速度是2L/min,第三分钟灌水的速度是3L/min,以此类推。而流水的速度固


下一篇:Vue中获取当前时间组件