How to format a duration in java? (e.g format H:MM:SS)

前端 未结 19 1507
情话喂你
情话喂你 2020-11-22 03:32

I\'d like to format a duration in seconds using a pattern like H:MM:SS. The current utilities in java are designed to format a time but not a duration.

19条回答
  •  情歌与酒
    2020-11-22 04:11

    How about the following function, which returns either +H:MM:SS or +H:MM:SS.sss

    public static String formatInterval(final long interval, boolean millisecs )
    {
        final long hr = TimeUnit.MILLISECONDS.toHours(interval);
        final long min = TimeUnit.MILLISECONDS.toMinutes(interval) %60;
        final long sec = TimeUnit.MILLISECONDS.toSeconds(interval) %60;
        final long ms = TimeUnit.MILLISECONDS.toMillis(interval) %1000;
        if( millisecs ) {
            return String.format("%02d:%02d:%02d.%03d", hr, min, sec, ms);
        } else {
            return String.format("%02d:%02d:%02d", hr, min, sec );
        }
    }
    

提交回复
热议问题