Java Time Format formatTime(long ms)

Here you can find the source of formatTime(long ms)

Description

format Time

License

Apache License

Declaration

public static String formatTime(long ms) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2015, 2016 Junichi Tatemura
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License./* www . j a  va  2  s .c  o m*/
 *******************************************************************************/

public class Main {
    public static final long MS_PER_SECOND = 1000;
    public static final long SECONDS_PER_MIN = 60;
    public static final long MIN_PER_HOUR = 60;
    public static final long HOURS_PER_DAY = 24;

    public static String formatTime(long ms) {
        long val = ms / MS_PER_SECOND;
        final int seconds = (int) (val % SECONDS_PER_MIN);
        val /= SECONDS_PER_MIN;
        final int minutes = (int) (val % MIN_PER_HOUR);
        val /= MIN_PER_HOUR;
        final int hours = (int) (val % HOURS_PER_DAY);
        val /= HOURS_PER_DAY;
        final int days = (int) val;

        StringBuilder sb = new StringBuilder();
        if (days > 1) {
            sb.append(days).append(" days ");
        } else if (days == 1) {
            sb.append("1 day ");
        }
        if (hours > 1) {
            sb.append(hours).append(" hours ");
        } else if (hours == 1) {
            sb.append("1 hour ");
        }
        if (minutes > 1) {
            sb.append(minutes).append(" minutes ");
        } else if (minutes == 1) {
            sb.append("1 minute ");
        }
        if (seconds > 1) {
            sb.append(seconds).append(" seconds");
        } else if (seconds == 1) {
            sb.append("1 second");
        }
        return sb.toString();
    }
}

Related

  1. formatTime(long millis)
  2. formatTime(long millis)
  3. formatTime(long millis)
  4. formatTime(long millis)
  5. formatTime(long millis, int precision)
  6. formatTime(long ms)
  7. formatTime(long msElapsed)
  8. formatTime(Long num)
  9. formatTime(long sec)