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

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

    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);
    }
    

提交回复
热议问题