src/share/classes/java/time/temporal/TemporalUnit.java

Print this page




  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time.temporal;
  63 
  64 import java.time.DateTimeException;
  65 import java.time.Duration;
  66 import java.time.Period;
  67 
  68 /**
  69  * A unit of date-time, such as Days or Hours.
  70  * <p>
  71  * Measurement of time is built on units, such as years, months, days, hours, minutes and seconds.
  72  * Implementations of this interface represent those units.
  73  * <p>
  74  * An instance of this interface represents the unit itself, rather than an amount of the unit.
  75  * See {@link Period} for a class that represents an amount in terms of the common units.
  76  * <p>
  77  * The most commonly used units are defined in {@link ChronoUnit}.
  78  * Further units are supplied in {@link ISOFields}.
  79  * Units can also be written by application code by implementing this interface.
  80  * <p>
  81  * The unit works using double dispatch. Client code calls methods on a date-time like
  82  * {@code LocalDateTime} which check if the unit is a {@code ChronoUnit}.
  83  * If it is, then the date-time must handle it.
  84  * Otherwise, the method call is re-dispatched to the matching method in this interface.
  85  *
  86  * <h3>Specification for implementors</h3>
  87  * This interface must be implemented with care to ensure other classes operate correctly.
  88  * All implementations that can be instantiated must be final, immutable and thread-safe.
  89  * It is recommended to use an enum where possible.
  90  *
  91  * @since 1.8
  92  */
  93 public interface TemporalUnit {
  94 
  95     /**
  96      * Gets a descriptive name for the unit.
  97      * <p>
  98      * This should be in the plural and upper-first camel case, such as 'Days' or 'Minutes'.
  99      *
 100      * @return the name, not null
 101      */
 102     String getName();
 103 
 104     /**
 105      * Gets the duration of this unit, which may be an estimate.
 106      * <p>
 107      * All units return a duration measured in standard nanoseconds from this method.

 108      * For example, an hour has a duration of {@code 60 * 60 * 1,000,000,000ns}.
 109      * <p>
 110      * Some units may return an accurate duration while others return an estimate.
 111      * For example, days have an estimated duration due to the possibility of
 112      * daylight saving time changes.
 113      * To determine if the duration is an estimate, use {@link #isDurationEstimated()}.
 114      *
 115      * @return the duration of this unit, which may be an estimate, not null
 116      */
 117     Duration getDuration();
 118 
 119     /**
 120      * Checks if the duration of the unit is an estimate.
 121      * <p>
 122      * All units have a duration, however the duration is not always accurate.
 123      * For example, days have an estimated duration due to the possibility of
 124      * daylight saving time changes.
 125      * This method returns true if the duration is an estimate and false if it is
 126      * accurate. Note that accurate/estimated ignores leap seconds.
 127      *
 128      * @return true if the duration is estimated, false if accurate
 129      */
 130     boolean isDurationEstimated();
 131 
 132     //-----------------------------------------------------------------------
 133     /**
 134      * Checks if this unit is supported by the specified temporal object.
 135      * <p>
 136      * This checks that the implementing date-time can add/subtract this unit.
 137      * This can be used to avoid throwing an exception.
 138      * <p>
 139      * This default implementation derives the value using
 140      * {@link Temporal#plus(long, TemporalUnit)}.
 141      *
 142      * @param temporal  the temporal object to check, not null
 143      * @return true if the unit is supported
 144      */
 145     public default boolean isSupported(Temporal temporal) {
 146         try {
 147             temporal.plus(1, this);
 148             return true;
 149         } catch (RuntimeException ex) {
 150             try {
 151                 temporal.plus(-1, this);
 152                 return true;
 153             } catch (RuntimeException ex2) {
 154                 return false;
 155             }
 156         }
 157     }
 158 
 159     /**
 160      * Returns a copy of the specified temporal object with the specified period added.
 161      * <p>
 162      * The period added is a multiple of this unit. For example, this method
 163      * could be used to add "3 days" to a date by calling this method on the
 164      * instance representing "days", passing the date and the period "3".
 165      * The period to be added may be negative, which is equivalent to subtraction.
 166      * <p>
 167      * There are two equivalent ways of using this method.
 168      * The first is to invoke this method directly.
 169      * The second is to use {@link Temporal#plus(long, TemporalUnit)}:
 170      * <pre>
 171      *   // these two lines are equivalent, but the second approach is recommended
 172      *   temporal = thisUnit.doPlus(temporal);
 173      *   temporal = temporal.plus(thisUnit);
 174      * </pre>
 175      * It is recommended to use the second approach, {@code plus(TemporalUnit)},
 176      * as it is a lot clearer to read in code.
 177      * <p>
 178      * Implementations should perform any queries or calculations using the units
 179      * available in {@link ChronoUnit} or the fields available in {@link ChronoField}.
 180      * If the field is not supported a {@code DateTimeException} must be thrown.
 181      * <p>
 182      * Implementations must not alter the specified temporal object.
 183      * Instead, an adjusted copy of the original must be returned.
 184      * This provides equivalent, safe behavior for immutable and mutable implementations.
 185      *
 186      * @param <R>  the type of the Temporal object
 187      * @param dateTime  the temporal object to adjust, not null
 188      * @param periodToAdd  the period of this unit to add, positive or negative
 189      * @return the adjusted temporal object, not null
 190      * @throws DateTimeException if the period cannot be added
 191      */
 192     <R extends Temporal> R doPlus(R dateTime, long periodToAdd);
 193 
 194     //-----------------------------------------------------------------------
 195     /**
 196      * Calculates the period in terms of this unit between two temporal objects of the same type.

 197      * <p>
 198      * The period will be positive if the second date-time is after the first, and
 199      * negative if the second date-time is before the first.
 200      * Call {@link SimplePeriod#abs() abs()} on the result to ensure that the result
 201      * is always positive.







 202      * <p>
 203      * The result can be queried for the {@link SimplePeriod#getAmount() amount}, the
 204      * {@link SimplePeriod#getUnit() unit} and used directly in addition/subtraction:










 205      * <pre>
 206      *  date = date.minus(MONTHS.between(start, end));


 207      * </pre>





 208      *
 209      * @param <R>  the type of the Temporal object; the two date-times must be of the same type
 210      * @param dateTime1  the base temporal object, not null
 211      * @param dateTime2  the other temporal object, not null
 212      * @return the period between datetime1 and datetime2 in terms of this unit;
 213      *      positive if datetime2 is later than datetime1, not null


 214      */
 215     <R extends Temporal> SimplePeriod between(R dateTime1, R dateTime2);
 216 
 217     //-----------------------------------------------------------------------
 218     /**
 219      * Outputs this unit as a {@code String} using the name.
 220      *
 221      * @return the name of this unit, not null
 222      */
 223     @Override
 224     String toString();
 225 
 226 }


  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time.temporal;
  63 
  64 import java.time.DateTimeException;
  65 import java.time.Duration;
  66 import java.time.Period;
  67 
  68 /**
  69  * A unit of date-time, such as Days or Hours.
  70  * <p>
  71  * Measurement of time is built on units, such as years, months, days, hours, minutes and seconds.
  72  * Implementations of this interface represent those units.
  73  * <p>
  74  * An instance of this interface represents the unit itself, rather than an amount of the unit.
  75  * See {@link Period} for a class that represents an amount in terms of the common units.
  76  * <p>
  77  * The most commonly used units are defined in {@link ChronoUnit}.
  78  * Further units are supplied in {@link IsoFields}.
  79  * Units can also be written by application code by implementing this interface.
  80  * <p>
  81  * The unit works using double dispatch. Client code calls methods on a date-time like
  82  * {@code LocalDateTime} which check if the unit is a {@code ChronoUnit}.
  83  * If it is, then the date-time must handle it.
  84  * Otherwise, the method call is re-dispatched to the matching method in this interface.
  85  *
  86  * <h3>Specification for implementors</h3>
  87  * This interface must be implemented with care to ensure other classes operate correctly.
  88  * All implementations that can be instantiated must be final, immutable and thread-safe.
  89  * It is recommended to use an enum where possible.
  90  *
  91  * @since 1.8
  92  */
  93 public interface TemporalUnit {
  94 
  95     /**
  96      * Gets a descriptive name for the unit.
  97      * <p>
  98      * This should be in the plural and upper-first camel case, such as 'Days' or 'Minutes'.
  99      *
 100      * @return the name, not null
 101      */
 102     String getName();
 103 
 104     /**
 105      * Gets the duration of this unit, which may be an estimate.
 106      * <p>
 107      * All units return a duration measured in standard nanoseconds from this method.
 108      * The duration will be positive and non-zero.
 109      * For example, an hour has a duration of {@code 60 * 60 * 1,000,000,000ns}.
 110      * <p>
 111      * Some units may return an accurate duration while others return an estimate.
 112      * For example, days have an estimated duration due to the possibility of
 113      * daylight saving time changes.
 114      * To determine if the duration is an estimate, use {@link #isDurationEstimated()}.
 115      *
 116      * @return the duration of this unit, which may be an estimate, not null
 117      */
 118     Duration getDuration();
 119 
 120     /**
 121      * Checks if the duration of the unit is an estimate.
 122      * <p>
 123      * All units have a duration, however the duration is not always accurate.
 124      * For example, days have an estimated duration due to the possibility of
 125      * daylight saving time changes.
 126      * This method returns true if the duration is an estimate and false if it is
 127      * accurate. Note that accurate/estimated ignores leap seconds.
 128      *
 129      * @return true if the duration is estimated, false if accurate
 130      */
 131     boolean isDurationEstimated();
 132 
 133     //-----------------------------------------------------------------------
 134     /**
 135      * Checks if this unit is supported by the specified temporal object.
 136      * <p>
 137      * This checks that the implementing date-time can add/subtract this unit.
 138      * This can be used to avoid throwing an exception.
 139      * <p>
 140      * This default implementation derives the value using
 141      * {@link Temporal#plus(long, TemporalUnit)}.
 142      *
 143      * @param temporal  the temporal object to check, not null
 144      * @return true if the unit is supported
 145      */
 146     public default boolean isSupportedBy(Temporal temporal) {
 147         try {
 148             temporal.plus(1, this);
 149             return true;
 150         } catch (RuntimeException ex) {
 151             try {
 152                 temporal.plus(-1, this);
 153                 return true;
 154             } catch (RuntimeException ex2) {
 155                 return false;
 156             }
 157         }
 158     }
 159 
 160     /**
 161      * Returns a copy of the specified temporal object with the specified period added.
 162      * <p>
 163      * The period added is a multiple of this unit. For example, this method
 164      * could be used to add "3 days" to a date by calling this method on the
 165      * instance representing "days", passing the date and the period "3".
 166      * The period to be added may be negative, which is equivalent to subtraction.
 167      * <p>
 168      * There are two equivalent ways of using this method.
 169      * The first is to invoke this method directly.
 170      * The second is to use {@link Temporal#plus(long, TemporalUnit)}:
 171      * <pre>
 172      *   // these two lines are equivalent, but the second approach is recommended
 173      *   temporal = thisUnit.addTo(temporal);
 174      *   temporal = temporal.plus(thisUnit);
 175      * </pre>
 176      * It is recommended to use the second approach, {@code plus(TemporalUnit)},
 177      * as it is a lot clearer to read in code.
 178      * <p>
 179      * Implementations should perform any queries or calculations using the units
 180      * available in {@link ChronoUnit} or the fields available in {@link ChronoField}.
 181      * If the unit is not supported a {@code DateTimeException} must be thrown.
 182      * <p>
 183      * Implementations must not alter the specified temporal object.
 184      * Instead, an adjusted copy of the original must be returned.
 185      * This provides equivalent, safe behavior for immutable and mutable implementations.
 186      *
 187      * @param <R>  the type of the Temporal object
 188      * @param temporal  the temporal object to adjust, not null
 189      * @param amount  the amount of this unit to add, positive or negative
 190      * @return the adjusted temporal object, not null
 191      * @throws DateTimeException if the period cannot be added
 192      */
 193     <R extends Temporal> R addTo(R temporal, long amount);
 194 
 195     //-----------------------------------------------------------------------
 196     /**
 197      * Calculates the period in terms of this unit between two temporal objects
 198      * of the same type.
 199      * <p>
 200      * This calculates the period between two temporals in terms of this unit.
 201      * The start and end points are supplied as temporal objects and must be
 202      * of the same type.
 203      * The result will be negative if the end is before the start.
 204      * For example, the period in hours between two temporal objects can be
 205      * calculated using {@code HOURS.between(startTime, endTime)}.
 206      * <p>
 207      * The calculation returns a whole number, representing the number of
 208      * complete units between the two temporals.
 209      * For example, the period in hours between the times 11:30 and 13:29
 210      * will only be one hour as it is one minute short of two hours.
 211      * <p>
 212      * There are two equivalent ways of using this method.
 213      * The first is to invoke this method directly.
 214      * The second is to use {@link Temporal#periodUntil(Temporal, TemporalUnit)}:
 215      * <pre>
 216      *   // these two lines are equivalent
 217      *   temporal = thisUnit.between(start, end);
 218      *   temporal = start.periodUntil(end, thisUnit);
 219      * </pre>
 220      * The choice should be made based on which makes the code more readable.
 221      * <p>
 222      * For example, this method allows the number of days between two dates to
 223      * be calculated:
 224      * <pre>
 225      *  long daysBetween = DAYS.between(start, end);
 226      *  // or alternatively
 227      *  long daysBetween = start.periodUntil(end, DAYS);
 228      * </pre>
 229      * <p>
 230      * Implementations should perform any queries or calculations using the units
 231      * available in {@link ChronoUnit} or the fields available in {@link ChronoField}.
 232      * If the unit is not supported a {@code DateTimeException} must be thrown.
 233      * Implementations must not alter the specified temporal objects.
 234      *
 235      * @param temporal1  the base temporal object, not null
 236      * @param temporal2  the other temporal object, not null

 237      * @return the period between datetime1 and datetime2 in terms of this unit;
 238      *  positive if datetime2 is later than datetime1, negative if earlier
 239      * @throws DateTimeException if the period cannot be calculated
 240      * @throws ArithmeticException if numeric overflow occurs
 241      */
 242     long between(Temporal temporal1, Temporal temporal2);
 243 
 244     //-----------------------------------------------------------------------
 245     /**
 246      * Outputs this unit as a {@code String} using the name.
 247      *
 248      * @return the name of this unit, not null
 249      */
 250     @Override
 251     String toString();
 252 
 253 }