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

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

    Based on @siddhadev's answer, I wrote a function which converts milliseconds to a formatted string:

       /**
         * Convert a millisecond duration to a string format
         * 
         * @param millis A duration to convert to a string form
         * @return A string of the form "X Days Y Hours Z Minutes A Seconds".
         */
        public static String getDurationBreakdown(long millis) {
            if(millis < 0) {
                throw new IllegalArgumentException("Duration must be greater than zero!");
            }
    
            long days = TimeUnit.MILLISECONDS.toDays(millis);
            millis -= TimeUnit.DAYS.toMillis(days);
            long hours = TimeUnit.MILLISECONDS.toHours(millis);
            millis -= TimeUnit.HOURS.toMillis(hours);
            long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
            millis -= TimeUnit.MINUTES.toMillis(minutes);
            long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
    
            StringBuilder sb = new StringBuilder(64);
            sb.append(days);
            sb.append(" Days ");
            sb.append(hours);
            sb.append(" Hours ");
            sb.append(minutes);
            sb.append(" Minutes ");
            sb.append(seconds);
            sb.append(" Seconds");
    
            return(sb.toString());
        }
    

提交回复
热议问题