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

后端 未结 27 1812
夕颜
夕颜 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:36

    I would not pull in the extra dependency just for that (division is not that hard, after all), but if you are using Commons Lang anyway, there are the DurationFormatUtils.

    Example Usage (adapted from here):

    import org.apache.commons.lang3.time.DurationFormatUtils
    
    public String getAge(long value) {
        long currentTime = System.currentTimeMillis();
        long age = currentTime - value;
        String ageString = DurationFormatUtils.formatDuration(age, "d") + "d";
        if ("0d".equals(ageString)) {
            ageString = DurationFormatUtils.formatDuration(age, "H") + "h";
            if ("0h".equals(ageString)) {
                ageString = DurationFormatUtils.formatDuration(age, "m") + "m";
                if ("0m".equals(ageString)) {
                    ageString = DurationFormatUtils.formatDuration(age, "s") + "s";
                    if ("0s".equals(ageString)) {
                        ageString = age + "ms";
                    }
                }
            }
        }
        return ageString;
    }   
    

    Example:

    long lastTime = System.currentTimeMillis() - 2000;
    System.out.println("Elapsed time: " + getAge(lastTime)); 
    
    //Output: 2s
    

    Note: To get millis from two LocalDateTime objects you can use:

    long age = ChronoUnit.MILLIS.between(initTime, LocalDateTime.now())
    

提交回复
热议问题