Java TimeUnit Usage humanizeTime(long hours, long minutes, long seconds)

Here you can find the source of humanizeTime(long hours, long minutes, long seconds)

Description

humanize Time

License

Apache License

Declaration

public static String humanizeTime(long hours, long minutes, long seconds) 

Method Source Code

//package com.java2s;
/*//  w w  w .j a  v  a  2s .  c o  m
 * Copyright (C) 2011 Near Infinity Corporation
 *
 * 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.
 */

import java.util.concurrent.TimeUnit;

public class Main {
    public static String humanizeTime(long time, TimeUnit unit) {
        long seconds = unit.toSeconds(time);
        long hours = getHours(seconds);
        seconds = seconds - TimeUnit.HOURS.toSeconds(hours);
        long minutes = getMinutes(seconds);
        seconds = seconds - TimeUnit.MINUTES.toSeconds(minutes);
        return humanizeTime(hours, minutes, seconds);
    }

    public static String humanizeTime(long hours, long minutes, long seconds) {
        StringBuilder builder = new StringBuilder();
        if (hours == 0 && minutes != 0) {
            addMinutes(builder, minutes);
        } else if (hours != 0) {
            addHours(builder, hours);
            addMinutes(builder, minutes);
        }
        addSeconds(builder, seconds);
        return builder.toString().trim();
    }

    private static long getHours(long seconds) {
        return seconds / TimeUnit.HOURS.toSeconds(1);
    }

    private static long getMinutes(long seconds) {
        return seconds / TimeUnit.MINUTES.toSeconds(1);
    }

    private static void addMinutes(StringBuilder builder, long minutes) {
        builder.append(minutes).append(" minutes ");
    }

    private static void addHours(StringBuilder builder, long hours) {
        builder.append(hours).append(" hours ");
    }

    private static void addSeconds(StringBuilder builder, long seconds) {
        builder.append(seconds).append(" seconds ");
    }
}

Related

  1. getTimezoneOffset(TimeZone timeZone)
  2. getTomorrowTimestamp()
  3. getUnit(long nanos)
  4. getValidityAsString(Date endDate)
  5. getWithTimeout(final Future future)
  6. humanizeToTime(long millis)
  7. humanReadableDuration(Date from, Date to)
  8. humanReadableMillis(long millis)
  9. isCurrentDateBeforeAndWithinRangeOfDate( Date date, int rangeInDays)