java 求两个时间的时间差

  public static String transferTimeTotal(Date time){
        //过去的时间(毫秒级)
        Long oldDate = time.getTime();
        //当前的时间(毫秒级)
        Long currentTime =new Date().getTime();
        //时间差(毫秒级)
        Long totalTime=currentTime-oldDate;
        
        long days = totalTime / (1000 * 60 * 60 * 24);
        long hours = (totalTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (totalTime % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (totalTime % (1000 * 60)) / 1000;
        return  days+"天"+ hours+ "时" + minutes + "分" + seconds+"秒";
    }

    public static void main(String[] args) throws ParseException {
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println( "12月1日至今,已有:"+transferTimeTotal(df.parse("2020-12-1 00:00:00")));
        System.out.println( "8月8日至今,已有:"+transferTimeTotal(df.parse("2020-8-8 00:00:00")));
    }

结果:

12月1日至今,已有:15天16时39分7秒
8月8日至今,已有:130天16时39分7秒

原文地址:https://www.cnblogs.com/javaLin/p/14144641.html