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

Print this page




  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  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  * @implSpec
  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     default boolean isSupportedBy(Temporal temporal) {









 147         try {
 148             temporal.plus(1, this);
 149             return true;
 150         } catch (UnsupportedTemporalTypeException ex) {
 151             return false;
 152         } catch (RuntimeException ex) {
 153             try {
 154                 temporal.plus(-1, this);
 155                 return true;
 156             } catch (RuntimeException ex2) {
 157                 return false;
 158             }
 159         }
 160     }
 161 
 162     /**
 163      * Returns a copy of the specified temporal object with the specified period added.
 164      * <p>
 165      * The period added is a multiple of this unit. For example, this method
 166      * could be used to add "3 days" to a date by calling this method on the


 195      */
 196     <R extends Temporal> R addTo(R temporal, long amount);
 197 
 198     //-----------------------------------------------------------------------
 199     /**
 200      * Calculates the amount of time between two temporal objects.
 201      * <p>
 202      * This calculates the amount in terms of this unit. The start and end
 203      * points are supplied as temporal objects and must be of the same type.
 204      * The result will be negative if the end is before the start.
 205      * For example, the amount in hours between two temporal objects can be
 206      * calculated using {@code HOURS.between(startTime, endTime)}.
 207      * <p>
 208      * The calculation returns a whole number, representing the number of
 209      * complete units between the two temporals.
 210      * For example, the amount in hours between the times 11:30 and 13:29
 211      * will only be one hour as it is one minute short of two hours.
 212      * <p>
 213      * There are two equivalent ways of using this method.
 214      * The first is to invoke this method directly.
 215      * The second is to use {@link Temporal#periodUntil(Temporal, TemporalUnit)}:
 216      * <pre>
 217      *   // these two lines are equivalent
 218      *   between = thisUnit.between(start, end);
 219      *   between = start.periodUntil(end, thisUnit);
 220      * </pre>
 221      * The choice should be made based on which makes the code more readable.
 222      * <p>
 223      * For example, this method allows the number of days between two dates to
 224      * be calculated:
 225      * <pre>
 226      *  long daysBetween = DAYS.between(start, end);
 227      *  // or alternatively
 228      *  long daysBetween = start.periodUntil(end, DAYS);
 229      * </pre>
 230      * <p>
 231      * Implementations should perform any queries or calculations using the units
 232      * available in {@link ChronoUnit} or the fields available in {@link ChronoField}.
 233      * If the unit is not supported an {@code UnsupportedTemporalTypeException} must be thrown.
 234      * Implementations must not alter the specified temporal objects.
 235      *
 236      * @param temporal1  the base temporal object, not null
 237      * @param temporal2  the other temporal object, not null
 238      * @return the amount of time between temporal1 and temporal2 in terms of this unit;
 239      *  positive if temporal2 is later than temporal1, negative if earlier
 240      * @throws DateTimeException if the amount cannot be calculated
 241      * @throws UnsupportedTemporalTypeException if the unit is not supported by the temporal
 242      * @throws ArithmeticException if numeric overflow occurs
 243      */
 244     long between(Temporal temporal1, Temporal temporal2);
 245 
 246     //-----------------------------------------------------------------------
 247     /**
 248      * Outputs this unit as a {@code String} using the name.


 249      *
 250      * @return the name of this unit, not null
 251      */
 252     @Override
 253     String toString();
 254 
 255 }


  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  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.LocalTime;
  67 import java.time.Period;
  68 import java.time.chrono.ChronoLocalDate;
  69 import java.time.chrono.ChronoLocalDateTime;
  70 import java.time.chrono.ChronoZonedDateTime;
  71 
  72 /**
  73  * A unit of date-time, such as Days or Hours.
  74  * <p>
  75  * Measurement of time is built on units, such as years, months, days, hours, minutes and seconds.
  76  * Implementations of this interface represent those units.
  77  * <p>
  78  * An instance of this interface represents the unit itself, rather than an amount of the unit.
  79  * See {@link Period} for a class that represents an amount in terms of the common units.
  80  * <p>
  81  * The most commonly used units are defined in {@link ChronoUnit}.
  82  * Further units are supplied in {@link IsoFields}.
  83  * Units can also be written by application code by implementing this interface.
  84  * <p>
  85  * The unit works using double dispatch. Client code calls methods on a date-time like
  86  * {@code LocalDateTime} which check if the unit is a {@code ChronoUnit}.
  87  * If it is, then the date-time must handle it.
  88  * Otherwise, the method call is re-dispatched to the matching method in this interface.
  89  *
  90  * @implSpec
  91  * This interface must be implemented with care to ensure other classes operate correctly.
  92  * All implementations that can be instantiated must be final, immutable and thread-safe.
  93  * It is recommended to use an enum where possible.
  94  *
  95  * @since 1.8
  96  */
  97 public interface TemporalUnit {
  98 
  99     /**









 100      * Gets the duration of this unit, which may be an estimate.
 101      * <p>
 102      * All units return a duration measured in standard nanoseconds from this method.
 103      * The duration will be positive and non-zero.
 104      * For example, an hour has a duration of {@code 60 * 60 * 1,000,000,000ns}.
 105      * <p>
 106      * Some units may return an accurate duration while others return an estimate.
 107      * For example, days have an estimated duration due to the possibility of
 108      * daylight saving time changes.
 109      * To determine if the duration is an estimate, use {@link #isDurationEstimated()}.
 110      *
 111      * @return the duration of this unit, which may be an estimate, not null
 112      */
 113     Duration getDuration();
 114 
 115     /**
 116      * Checks if the duration of the unit is an estimate.
 117      * <p>
 118      * All units have a duration, however the duration is not always accurate.
 119      * For example, days have an estimated duration due to the possibility of
 120      * daylight saving time changes.
 121      * This method returns true if the duration is an estimate and false if it is
 122      * accurate. Note that accurate/estimated ignores leap seconds.
 123      *
 124      * @return true if the duration is estimated, false if accurate
 125      */
 126     boolean isDurationEstimated();
 127 
 128     //-----------------------------------------------------------------------
 129     /**
 130      * Checks if this unit represents a component of a date.
 131      * <p>
 132      * A date is time-based if it can be used to imply meaning from a date.
 133      * It must have a {@linkplain #getDuration() duration} that is an integral
 134      * multiple of the length of a standard day.
 135      * Note that it is valid for both {@code isDateBased()} and {@code isTimeBased()}
 136      * to return false, such as when representing a unit like 36 hours.
 137      *
 138      * @return true if this unit is a component of a date
 139      */
 140     boolean isDateBased();
 141 
 142     /**
 143      * Checks if this unit represents a component of a time.
 144      * <p>
 145      * A unit is time-based if it can be used to imply meaning from a time.
 146      * It must have a {@linkplain #getDuration() duration} that divides into
 147      * the length of a standard day without remainder.
 148      * Note that it is valid for both {@code isDateBased()} and {@code isTimeBased()}
 149      * to return false, such as when representing a unit like 36 hours.
 150      *
 151      * @return true if this unit is a component of a time
 152      */
 153     boolean isTimeBased();
 154 
 155     //-----------------------------------------------------------------------
 156     /**
 157      * Checks if this unit is supported by the specified temporal object.
 158      * <p>
 159      * This checks that the implementing date-time can add/subtract this unit.
 160      * This can be used to avoid throwing an exception.
 161      * <p>
 162      * This default implementation derives the value using
 163      * {@link Temporal#plus(long, TemporalUnit)}.
 164      *
 165      * @param temporal  the temporal object to check, not null
 166      * @return true if the unit is supported
 167      */
 168     default boolean isSupportedBy(Temporal temporal) {
 169         if (temporal instanceof LocalTime) {
 170             return isTimeBased();
 171         }
 172         if (temporal instanceof ChronoLocalDate) {
 173             return isDateBased();
 174         }
 175         if (temporal instanceof ChronoLocalDateTime || temporal instanceof ChronoZonedDateTime) {
 176             return true;
 177         }
 178         try {
 179             temporal.plus(1, this);
 180             return true;
 181         } catch (UnsupportedTemporalTypeException ex) {
 182             return false;
 183         } catch (RuntimeException ex) {
 184             try {
 185                 temporal.plus(-1, this);
 186                 return true;
 187             } catch (RuntimeException ex2) {
 188                 return false;
 189             }
 190         }
 191     }
 192 
 193     /**
 194      * Returns a copy of the specified temporal object with the specified period added.
 195      * <p>
 196      * The period added is a multiple of this unit. For example, this method
 197      * could be used to add "3 days" to a date by calling this method on the


 226      */
 227     <R extends Temporal> R addTo(R temporal, long amount);
 228 
 229     //-----------------------------------------------------------------------
 230     /**
 231      * Calculates the amount of time between two temporal objects.
 232      * <p>
 233      * This calculates the amount in terms of this unit. The start and end
 234      * points are supplied as temporal objects and must be of the same type.
 235      * The result will be negative if the end is before the start.
 236      * For example, the amount in hours between two temporal objects can be
 237      * calculated using {@code HOURS.between(startTime, endTime)}.
 238      * <p>
 239      * The calculation returns a whole number, representing the number of
 240      * complete units between the two temporals.
 241      * For example, the amount in hours between the times 11:30 and 13:29
 242      * will only be one hour as it is one minute short of two hours.
 243      * <p>
 244      * There are two equivalent ways of using this method.
 245      * The first is to invoke this method directly.
 246      * The second is to use {@link Temporal#until(Temporal, TemporalUnit)}:
 247      * <pre>
 248      *   // these two lines are equivalent
 249      *   between = thisUnit.between(start, end);
 250      *   between = start.until(end, thisUnit);
 251      * </pre>
 252      * The choice should be made based on which makes the code more readable.
 253      * <p>
 254      * For example, this method allows the number of days between two dates to
 255      * be calculated:
 256      * <pre>
 257      *  long daysBetween = DAYS.between(start, end);
 258      *  // or alternatively
 259      *  long daysBetween = start.until(end, DAYS);
 260      * </pre>
 261      * <p>
 262      * Implementations should perform any queries or calculations using the units
 263      * available in {@link ChronoUnit} or the fields available in {@link ChronoField}.
 264      * If the unit is not supported an {@code UnsupportedTemporalTypeException} must be thrown.
 265      * Implementations must not alter the specified temporal objects.
 266      *
 267      * @param temporal1  the base temporal object, not null
 268      * @param temporal2  the other temporal object, not null
 269      * @return the amount of time between temporal1 and temporal2 in terms of this unit;
 270      *  positive if temporal2 is later than temporal1, negative if earlier
 271      * @throws DateTimeException if the amount cannot be calculated
 272      * @throws UnsupportedTemporalTypeException if the unit is not supported by the temporal
 273      * @throws ArithmeticException if numeric overflow occurs
 274      */
 275     long between(Temporal temporal1, Temporal temporal2);
 276 
 277     //-----------------------------------------------------------------------
 278     /**
 279      * Gets a descriptive name for the unit.
 280      * <p>
 281      * This should be in the plural and upper-first camel case, such as 'Days' or 'Minutes'.
 282      *
 283      * @return the name of this unit, not null
 284      */
 285     @Override
 286     String toString();
 287 
 288 }