// // FILE: TimePrinter.java // AUTHOR: Eugene Wallingford // DATE: 10/05/06 // COMMENT: A very quick-and-dirty way to print out the number of // years, months, days, hours, and seconds in a given // number of seconds. The style is this program is // not good at all -- it can be made more efficient // and easier to read. Do not use this as an example // for your own programs. // // Usage: TimePrinter.toString( long ) // TimePrinter.toStringFromDouble( long ) // public class TimePrinter { private static final long MINUTE = 60; private static final long HOUR = 60 * 60; private static final long DAY = 24 * 60 * 60; private static final long MONTH = (long) ( 30.41666 * 24 * 60 * 60); private static final long YEAR = (long) (365.25000 * 24 * 60 * 60); public static String toString( long secondsRemaining ) { String answer = ""; while ( secondsRemaining > 0 ) { if ( secondsRemaining > YEAR ) { long nextValue = secondsRemaining / YEAR; secondsRemaining = secondsRemaining % YEAR; answer = answer + nextValue + " years "; } else if ( secondsRemaining > MONTH ) { long nextValue = secondsRemaining / MONTH; secondsRemaining = secondsRemaining % MONTH; answer = answer + nextValue + " months "; } else if ( secondsRemaining > DAY ) { long nextValue = secondsRemaining / DAY; secondsRemaining = secondsRemaining % DAY; answer = answer + nextValue + " days "; } else if ( secondsRemaining > HOUR ) { long nextValue = secondsRemaining / HOUR; secondsRemaining = secondsRemaining % HOUR; answer = answer + nextValue + " hours "; } else if ( secondsRemaining > MINUTE ) { long nextValue = secondsRemaining / MINUTE; secondsRemaining = secondsRemaining % MINUTE; answer = answer + nextValue + " minutes "; } else { answer = answer + secondsRemaining + " seconds"; secondsRemaining = 0; } } return answer; } public static String toStringFromDouble( double secondsRemaining ) { String answer = ""; while ( secondsRemaining > 0 ) { if ( secondsRemaining > YEAR ) { long nextValue = (long) secondsRemaining / YEAR; secondsRemaining = secondsRemaining - nextValue * YEAR; answer = answer + nextValue + " years "; } else if ( secondsRemaining > MONTH ) { long nextValue = (long) secondsRemaining / MONTH; secondsRemaining = secondsRemaining - nextValue * MONTH; answer = answer + nextValue + " months "; } else if ( secondsRemaining > DAY ) { long nextValue = (long) secondsRemaining / DAY; secondsRemaining = secondsRemaining - nextValue * DAY; answer = answer + nextValue + " days "; } else if ( secondsRemaining > HOUR ) { long nextValue = (long) secondsRemaining / HOUR; secondsRemaining = secondsRemaining - nextValue * HOUR; answer = answer + nextValue + " hours "; } else if ( secondsRemaining > MINUTE ) { long nextValue = (long) secondsRemaining / MINUTE; secondsRemaining = secondsRemaining - nextValue * MINUTE; answer = answer + nextValue + " minutes "; } else { answer = answer + secondsRemaining + " seconds"; secondsRemaining = 0; } } return answer; } }