Skip to main content

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



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 System.currentTimeMillis() from the start variable, and I want to show them the time elapsed using a human readable format such as "XX hours, XX mins, XX seconds" or even "XX mins, XX seconds" because its not likely to take someone an hour.





What's the best way to do this?


Comments

  1. Since 1.5 there is the java.util.concurrent.TimeUnit class, use it like this:

    String.format("%d min, %d sec",
    TimeUnit.MILLISECONDS.toMinutes(millis),
    TimeUnit.MILLISECONDS.toSeconds(millis) -
    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
    );


    For Java versions below 1.5 or for systems that do not fully support the TimeUnit class (such as Android before API version 9), the following equations can be used:

    int seconds = (int) (milliseconds / 1000) % 60 ;
    int minutes = (int) ((milliseconds / (1000*60)) % 60);
    int hours = (int) ((milliseconds / (1000*60*60)) % 24);


    //etc...

    ReplyDelete
  2. Uhm... how many milliseconds are in a second? And in a minute? Division is not that hard.

    int seconds = (int) ((milliseconds / 1000) % 60);
    int minutes = (int) ((milliseconds / 1000) / 60);


    Continue like that for hours, days, weeks, months, year, decades, whatever.

    ReplyDelete
  3. Either hand divisions, or use the SimpleDateFormat API.

    long start = System.currentTimeMillis();
    // do your work...
    long elapsed = System.currentTimeMillis() - start;
    DateFormat df = new SimpleDateFormat("HH 'hours', mm 'mins,' ss 'seconds'");
    df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
    System.out.println(df.format(new Date(elapsed)));


    Edit by Bombe: It has been shown in the comments that this approach only works for smaller durations (i.e. less than a day).

    ReplyDelete
  4. 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.

    ReplyDelete
  5. Based on @siddhadev's answer, I wrote a function to do this recently. Just thought I'd share in case anyone finds it useful:

    /**
    * 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());
    }


    Enjoy!

    ReplyDelete
  6. Just to add more info
    if you want to format like: HH:mm:ss

    0 <= HH <= infinite

    0 <= mm < 60

    0 <= ss < 60

    use this:

    int h = (int) ((startTimeInMillis / 1000) / 3600);
    int m = (int) (((startTimeInMillis / 1000) / 60) % 60);
    int s = (int) ((startTimeInMillis / 1000) % 60);


    I just had this issue now and figured this out

    ReplyDelete
  7. division is easy BUT does not easily display a leading zero when needed.
    (say : pretty print 5min08sec)

    I feel like simpledateformat is better suited for that, am I wrong ?

    ReplyDelete
  8. For small times, less than an hour, I prefer:

    long millis = ...

    System.out.printf("%1$TM:%1$TS", millis);
    // or
    String str = String.format("%1$TM:%1$TS", millis);


    for longer intervalls:

    private static final long HOUR = TimeUnit.HOURS.toMillis(1);
    ...
    if (millis < HOUR) {
    System.out.printf("%1$TM:%1$TS%n", millis);
    } else {
    System.out.printf("%d:%2$TM:%2$TS%n", millis / HOUR, millis % HOUR);
    }

    ReplyDelete
  9. I think the best way is:

    String.format("%d min, %d sec",
    TimeUnit.MILLISECONDS.toSeconds(length)/60,
    TimeUnit.MILLISECONDS.toSeconds(length) % 60 );

    ReplyDelete
  10. for correct strings ("1hour, 3sec", "3 min" but not "0 hour, 0 min, 3 sec") i write this code:

    int seconds = (int)(millis / 1000) % 60 ;
    int minutes = (int)((millis / (1000*60)) % 60);
    int hours = (int)((millis / (1000*60*60)) % 24);
    int days = (int)((millis / (1000*60*60*24)) % 365);
    int years = (int)(millis / 1000*60*60*24*365);

    ArrayList<String> timeArray = new ArrayList<String>();

    if(years > 0)
    timeArray.add(String.valueOf(years) + "y");

    if(days > 0)
    timeArray.add(String.valueOf(days) + "d");

    if(hours>0)
    timeArray.add(String.valueOf(hours) + "h");

    if(minutes>0)
    timeArray.add(String.valueOf(minutes) + "min");

    if(seconds>0)
    timeArray.add(String.valueOf(seconds) + "sec");

    String time = "";
    for (int i = 0; i < timeArray.size(); i++)
    {
    time = time + timeArray.get(i);
    if (i != timeArray.size() - 1)
    time = time + ", ";
    }

    if (time == "")
    time = "0 sec";

    ReplyDelete
  11. long time = 1536259;
    ...
    return (new SimpleDateFormat("mm:ss:SSS")).format(new Date(time));

    ==> 25:36:259

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?