How to convert Milliseconds to “X mins, x seconds” in Java?

后端 未结 27 2336
夕颜
夕颜 2020-11-22 03:59

I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current Syste

27条回答
  •  半阙折子戏
    2020-11-22 04:22

    Use java.util.concurrent.TimeUnit, and use this simple method:

    private static long timeDiff(Date date, Date date2, TimeUnit unit) {
        long milliDiff=date2.getTime()-date.getTime();
        long unitDiff = unit.convert(milliDiff, TimeUnit.MILLISECONDS);
        return unitDiff; 
    }
    

    For example:

    SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd HH:mm:ss");  
    Date firstDate = sdf.parse("06/24/2017 04:30:00");
    Date secondDate = sdf.parse("07/24/2017 05:00:15");
    Date thirdDate = sdf.parse("06/24/2017 06:00:15");
    
    System.out.println("days difference: "+timeDiff(firstDate,secondDate,TimeUnit.DAYS));
    System.out.println("hours difference: "+timeDiff(firstDate,thirdDate,TimeUnit.HOURS));
    System.out.println("minutes difference: "+timeDiff(firstDate,thirdDate,TimeUnit.MINUTES));
    System.out.println("seconds difference: "+timeDiff(firstDate,thirdDate,TimeUnit.SECONDS));
    

提交回复
热议问题