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

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

    I modified @MyKuLLSKI 's answer and added plurlization support. I took out seconds because I didn't need them, though feel free to re-add it if you need it.

    public static String intervalToHumanReadableTime(int intervalMins) {
    
        if(intervalMins <= 0) {
            return "0";
        } else {
    
            long intervalMs = intervalMins * 60 * 1000;
    
            long days = TimeUnit.MILLISECONDS.toDays(intervalMs);
            intervalMs -= TimeUnit.DAYS.toMillis(days);
            long hours = TimeUnit.MILLISECONDS.toHours(intervalMs);
            intervalMs -= TimeUnit.HOURS.toMillis(hours);
            long minutes = TimeUnit.MILLISECONDS.toMinutes(intervalMs);
    
            StringBuilder sb = new StringBuilder(12);
    
            if (days >= 1) {
                sb.append(days).append(" day").append(pluralize(days)).append(", ");
            }
    
            if (hours >= 1) {
                sb.append(hours).append(" hour").append(pluralize(hours)).append(", ");
            }
    
            if (minutes >= 1) {
                sb.append(minutes).append(" minute").append(pluralize(minutes));
            } else {
                sb.delete(sb.length()-2, sb.length()-1);
            }
    
            return(sb.toString());          
    
        }
    
    }
    
    public static String pluralize(long val) {
        return (Math.round(val) > 1 ? "s" : "");
    }
    

提交回复
热议问题