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

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex