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

后端 未结 27 1855
夕颜
夕颜 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条回答
  •  梦毁少年i
    2020-11-22 04:19

    Revisiting @brent-nash contribution, we could use modulus function instead of subtractions and use String.format method for the result 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 B Milliseconds".
       */
       public static String getDurationBreakdown(long millis) {
           if (millis < 0) {
              throw new IllegalArgumentException("Duration must be greater than zero!");
           }
    
           long days = TimeUnit.MILLISECONDS.toDays(millis);
           long hours = TimeUnit.MILLISECONDS.toHours(millis) % 24;
           long minutes = TimeUnit.MILLISECONDS.toMinutes(millis) % 60;
           long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) % 60;
           long milliseconds = millis % 1000;
    
           return String.format("%d Days %d Hours %d Minutes %d Seconds %d Milliseconds",
                                days, hours, minutes, seconds, milliseconds);
       }
    

提交回复
热议问题