/* * [TimeInterval.java] * * Summary: display a number as a time interval in words in milliseconds. * * Copyright: (c) 1999-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.0 1999-01-17 initial version. */ package com.mindprod.inwords; /** * display a number as a time interval in words in milliseconds. * * @author Roedy Green, Canadian Mind Products * @version 1.0 1999-01-17 initial version. * @since 1999-01-17 */ public final class TimeInterval implements ToWords { private static final int FIRST_COPYRIGHT_YEAR = 1999; /** * undisplayed copyright notice * * @noinspection UnusedDeclaration */ private static final String EMBEDDED_COPYRIGHT = "Copyright: (c) 1999-2017 Roedy Green, Canadian Mind Products, http://mindprod.com"; private static final String[] pluralGroupName = { "milliseconds", "centiseconds", "tenths of a second", "seconds", "minutes", "hours", "days" }; private static final String[] singularGroupName = { "millisecond", "centisecond", "tenth of a second", "second", "minute", "hour", "day" }; private static final int[] divisor = { 10, 10, 10, 60, 60, 24, 2147483647 }; /** * test harness * * @param args not used */ public static void main( String[] args ) { Test.test( new TimeInterval() ); } // end main /** * get time is words e.g. "none" "1 millisecond" "2 milliseconds" "1 hundredth of a second" "2 tenths of a second", * "6 seconds", "59 seconds", "1 minute and 10 seconds", "1 hour and 10 minutes" "48 hours", "3 days" * * @param num time in milliseconds, must be positive. * * @return approximate time difference in words. */ @SuppressWarnings( { "WeakerAccess" } ) public String toWords( long num ) { if ( num < 0 ) { return "negative"; } if ( num == 0 ) { return "none"; } String s = ""; // find highest group we will display int highest = 0; int lowest; long saveNum = num; for ( int group = 0; num > 0; group++ ) { int remdr = ( int ) ( num % divisor[ group ] ); num = num / divisor[ group ]; if ( remdr != 0 ) { highest = group; } } // end for // find lowest group we will display. if ( highest > 3 ) { lowest = highest - 1; if ( lowest < 0 ) { lowest = 0; } } else { lowest = highest; } num = saveNum; for ( int i = 0; num > 0; i++ ) { int remdr = ( int ) ( num % divisor[ i ] ); num = num / divisor[ i ]; if ( remdr == 0 ) { continue; } if ( i < lowest ) { // possibly round up. if ( i == lowest - 1 && remdr > divisor[ i ] / 2 ) { num++; } } else { String t = Integer.toString( remdr ); boolean plural = ( remdr > 1 ); boolean needAnd = ( s.length() != 0 ); s = t + " " + ( plural ? pluralGroupName[ i ] : singularGroupName[ i ] ) + ( needAnd ? " and " : "" ) + s; } } // end for return s; } // end inWords } // end TimeInterval