编程语言
首页 > 编程语言> > 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

标签:java,hour,long,时间差,计算,diff,day,minute
来源: https://www.cnblogs.com/d534/p/15649405.html