java两个时间段计算相差时长

计算两个时间段相差时长

复制代码
public static String getDistanceTime(Long  str1 ,Long str2) {
        long day = 0;//天数差
        long hour = 0;//小时数差
        long min = 0;//分钟数差
        long second=0;//秒数差
        long diff=0 ;//毫秒差
        StringBuilder result =new StringBuilder();
        //String result = "";
        diff = str2-str1;
        day = diff / (24 * 60 * 60 * 1000);
        hour = (diff / (60 * 60 * 1000) - day * 24);
        min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        second = diff/1000;
        System.out.println("day="+day+" hour="+hour+" min="+min+" ss="+second%60+" SSS="+diff%1000);
        String daystr = day%30+"天";
        String hourStr = hour%24+"小时";
        String minStr = min%60+"分";
        String secondStr = second%60+"秒";
        if (day!=0){
            result.append(daystr);
            //result = result + daystr;
        }
        if (hour!=0){
            result.append(hourStr);
            //result = result + hourStr;
        }
        if (min!=0){
            result.append(minStr);
            //result = result + minStr;
        }
        if (second!=0){
            result.append(secondStr);
            //result = result + secondStr;
        }
        return result.toString();
    }

创建主方法

复制代码
public static void main(String[] args) throws ParseException {
        String a="2023-07-27 14:43:00";
        String b="2023-07-28 14:30:10";
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse1 = dateFormat.parse(a);
        Date parse2 = dateFormat.parse(b);
        String bigDecimal=getDistanceTime(parse1.getTime(),parse2.getTime());
        System.out.println(bigDecimal);
      
    }

运行结果

相关推荐
seven97_top6 分钟前
两小时入门Sentinel
java·sentinel
叶小鸡6 分钟前
Java 篇-项目实战-AI 天机学堂(从 0 到 1)-day1
java·开发语言
bigbearxyz17 分钟前
Caused by: java.net.SocketException: Connection reset问题排查
java·keepalived·proxysql
Daydream.V26 分钟前
Python Flask超全入门实战教程|从零基础到项目部署
大数据·python·flask
databook1 小时前
Manim物理模拟:别自己写欧拉了!
python·数学·动效
楼田莉子2 小时前
C++17新特性:__had_include/属性/求值顺序规则
开发语言·c++·后端
香蕉鼠片2 小时前
Python进阶学习
开发语言·python
500842 小时前
昇腾 CANN 的五层架构,到底分了哪五层
java·人工智能·分布式·架构·ocr·wpf
摇滚侠2 小时前
Java 零基础全套教程,File 类与 IO 流,笔记 177-178
java·开发语言·笔记
ytttr8733 小时前
OPC UA 协议栈 C 语言实现
c语言·开发语言·mfc