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秒

posted @ 2020-12-16 16:36  信息界的搬运工  阅读(929)  评论(0编辑  收藏  举报