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 */ 017package org.apache.activemq.util; 018 019import java.text.DecimalFormat; 020import java.text.DecimalFormatSymbols; 021import java.text.NumberFormat; 022import java.util.Locale; 023 024/** 025 * Time utilities. 026 */ 027public final class TimeUtils { 028 029 private TimeUtils() { 030 } 031 032 /** 033 * Prints the duration in a human readable format as X days Y hours Z minutes etc. 034 * 035 * @param uptime the up-time in milliseconds 036 * 037 * @return the time used for displaying on screen or in logs 038 */ 039 public static String printDuration(double uptime) { 040 // Code taken from Karaf 041 // https://svn.apache.org/repos/asf/karaf/trunk/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/InfoAction.java 042 043 NumberFormat fmtI = new DecimalFormat("###,###", new DecimalFormatSymbols(Locale.ENGLISH)); 044 NumberFormat fmtD = new DecimalFormat("###,##0.000", new DecimalFormatSymbols(Locale.ENGLISH)); 045 046 uptime /= 1000; 047 if (uptime < 60) { 048 return fmtD.format(uptime) + " seconds"; 049 } 050 uptime /= 60; 051 if (uptime < 60) { 052 long minutes = (long) uptime; 053 String s = fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute"); 054 return s; 055 } 056 uptime /= 60; 057 if (uptime < 24) { 058 long hours = (long) uptime; 059 long minutes = (long) ((uptime - hours) * 60); 060 String s = fmtI.format(hours) + (hours > 1 ? " hours" : " hour"); 061 if (minutes != 0) { 062 s += " " + fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute"); 063 } 064 return s; 065 } 066 uptime /= 24; 067 long days = (long) uptime; 068 long hours = (long) ((uptime - days) * 24); 069 String s = fmtI.format(days) + (days > 1 ? " days" : " day"); 070 if (hours != 0) { 071 s += " " + fmtI.format(hours) + (hours > 1 ? " hours" : " hour"); 072 } 073 074 return s; 075 } 076}