package com.onaro.util.jfc.date; import java.util.concurrent.TimeUnit; /** * Immutable class that computes an age (duration since * an event) and provides methods to display * the age. The age is not dynamic; it is determined * when an instance of the class is created. */ public class Age implements Comparable { private static final long TWO_DAYS = TimeUnit.DAYS.toMillis (2); private static final long TWO_HOURS = TimeUnit.HOURS.toMillis (2); private static final long TWO_MINUTES = TimeUnit.MINUTES.toMillis (2); private static final long TWO_SECONDS = TimeUnit.SECONDS.toMillis (2); private final long age; /** * Create {@link Age} whose value is the time * since the specified birth time. * @param birth time that should be considered age 0 */ public Age (long birth) { age = System.currentTimeMillis() - birth; } /** * Gets the age in milliseconds. * @return the age */ public long getAge() { return age; } /** * Gets the age in the given time unit. * @param unit time unit enumerator * @return the age converted to the specified unit */ public long getAge (TimeUnit unit) { return unit.convert (age, TimeUnit.MILLISECONDS); } /** * Gets the age as a displayable string. The format is: * */ public String getDisplayText() { if (age >= TWO_DAYS) { return Messages.INSTANCE.getDays (getAge (TimeUnit.DAYS)); } if (age >= TWO_HOURS) { return Messages.INSTANCE.getHours (getAge (TimeUnit.HOURS)); } if (age >= TWO_MINUTES) { return Messages.INSTANCE.getMinutes (getAge (TimeUnit.MINUTES)); } if (age >= TWO_SECONDS) { return Messages.INSTANCE.getSeconds (getAge (TimeUnit.SECONDS)); } return Messages.INSTANCE.getMillis (age); } @Override public boolean equals (Object that) { return that instanceof Age && this.age == ((Age)that).age; } @Override public int hashCode() { return Long.valueOf(age).hashCode(); } @Override public String toString() { return Long.toString (age); } @Override public int compareTo (Age that) { return (int)(this.age - that.age); } }