001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.util;
018
019 import java.text.DecimalFormat;
020 import java.text.DecimalFormatSymbols;
021 import java.text.NumberFormat;
022 import java.util.Locale;
023
024 /**
025 * Time utils.
026 *
027 * @version
028 */
029 public final class TimeUtils {
030
031 private TimeUtils() {
032 }
033
034 /**
035 * Prints the duration in a human readable format as X days Y hours Z minutes etc.
036 *
037 * @param uptime the uptime in millis
038 * @return the time used for displaying on screen or in logs
039 */
040 public static String printDuration(double uptime) {
041 // Code taken from Karaf
042 // https://svn.apache.org/repos/asf/karaf/trunk/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/InfoAction.java
043
044 NumberFormat fmtI = new DecimalFormat("###,###", new DecimalFormatSymbols(Locale.ENGLISH));
045 NumberFormat fmtD = new DecimalFormat("###,##0.000", new DecimalFormatSymbols(Locale.ENGLISH));
046
047 uptime /= 1000;
048 if (uptime < 60) {
049 return fmtD.format(uptime) + " seconds";
050 }
051 uptime /= 60;
052 if (uptime < 60) {
053 long minutes = (long) uptime;
054 String s = fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
055 return s;
056 }
057 uptime /= 60;
058 if (uptime < 24) {
059 long hours = (long) uptime;
060 long minutes = (long) ((uptime - hours) * 60);
061 String s = fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
062 if (minutes != 0) {
063 s += " " + fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
064 }
065 return s;
066 }
067 uptime /= 24;
068 long days = (long) uptime;
069 long hours = (long) ((uptime - days) * 24);
070 String s = fmtI.format(days) + (days > 1 ? " days" : " day");
071 if (hours != 0) {
072 s += " " + fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
073 }
074 return s;
075 }
076
077 }