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

后端 未结 27 1837
夕颜
夕颜 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())
    
    0 讨论(0)
  • 2020-11-22 04:36

    My simple calculation:

    String millisecToTime(int millisec) {
        int sec = millisec/1000;
        int second = sec % 60;
        int minute = sec / 60;
        if (minute >= 60) {
            int hour = minute / 60;
            minute %= 60;
            return hour + ":" + (minute < 10 ? "0" + minute : minute) + ":" + (second < 10 ? "0" + second : second);
        }
        return minute + ":" + (second < 10 ? "0" + second : second);
    }
    

    Happy coding :)

    0 讨论(0)
  • 2020-11-22 04:37

    This answer is similar to some answers above. However, I feel that it would be beneficial because, unlike other answers, this will remove any extra commas or whitespace and handles abbreviation.

    /**
     * Converts milliseconds to "x days, x hours, x mins, x secs"
     * 
     * @param millis
     *            The milliseconds
     * @param longFormat
     *            {@code true} to use "seconds" and "minutes" instead of "secs" and "mins"
     * @return A string representing how long in days/hours/minutes/seconds millis is.
     */
    public static String millisToString(long millis, boolean longFormat) {
        if (millis < 1000) {
            return String.format("0 %s", longFormat ? "seconds" : "secs");
        }
        String[] units = {
                "day", "hour", longFormat ? "minute" : "min", longFormat ? "second" : "sec"
        };
        long[] times = new long[4];
        times[0] = TimeUnit.DAYS.convert(millis, TimeUnit.MILLISECONDS);
        millis -= TimeUnit.MILLISECONDS.convert(times[0], TimeUnit.DAYS);
        times[1] = TimeUnit.HOURS.convert(millis, TimeUnit.MILLISECONDS);
        millis -= TimeUnit.MILLISECONDS.convert(times[1], TimeUnit.HOURS);
        times[2] = TimeUnit.MINUTES.convert(millis, TimeUnit.MILLISECONDS);
        millis -= TimeUnit.MILLISECONDS.convert(times[2], TimeUnit.MINUTES);
        times[3] = TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            if (times[i] > 0) {
                s.append(String.format("%d %s%s, ", times[i], units[i], times[i] == 1 ? "" : "s"));
            }
        }
        return s.toString().substring(0, s.length() - 2);
    }
    
    /**
     * Converts milliseconds to "x days, x hours, x mins, x secs"
     * 
     * @param millis
     *            The milliseconds
     * @return A string representing how long in days/hours/mins/secs millis is.
     */
    public static String millisToString(long millis) {
        return millisToString(millis, false);
    }
    
    0 讨论(0)
提交回复
热议问题