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

后端 未结 27 1801
夕颜
夕颜 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

    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).

提交回复
热议问题