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

Print this page




  45  *
  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.ZoneId;
  66 
  67 /**
  68  * Framework-level interface defining read-write access to a temporal object,
  69  * such as a date, time, offset or some combination of these.
  70  * <p>
  71  * This is the base interface type for date, time and offset objects that
  72  * are complete enough to be manipulated using plus and minus.
  73  * It is implemented by those classes that can provide and manipulate information
  74  * as {@linkplain TemporalField fields} or {@linkplain TemporalQuery queries}.
  75  * See {@link TemporalAccessor} for the read-only version of this interface.
  76  * <p>
  77  * Most date and time information can be represented as a number.
  78  * These are modeled using {@code TemporalField} with the number held using
  79  * a {@code long} to handle large values. Year, month and day-of-month are
  80  * simple examples of fields, but they also include instant and offsets.
  81  * See {@link ChronoField} for the standard set of fields.
  82  * <p>
  83  * Two pieces of date/time information cannot be represented by numbers,
  84  * the {@linkplain java.time.chrono.Chronology chronology} and the {@linkplain ZoneId time-zone}.

  85  * These can be accessed via {@link #query(TemporalQuery) queries} using
  86  * the static methods defined on {@link TemporalQuery}.
  87  * <p>
  88  * This interface is a framework-level interface that should not be widely
  89  * used in application code. Instead, applications should create and pass
  90  * around instances of concrete types, such as {@code LocalDate}.
  91  * There are many reasons for this, part of which is that implementations
  92  * of this interface may be in calendar systems other than ISO.
  93  * See {@link java.time.chrono.ChronoLocalDate} for a fuller discussion of the issues.
  94  *
  95  * <h3>When to implement</h3>
  96  * <p>
  97  * A class should implement this interface if it meets three criteria:
  98  * <p><ul>
  99  * <li>it provides access to date/time/offset information, as per {@code TemporalAccessor}
 100  * <li>the set of fields are contiguous from the largest to the smallest
 101  * <li>the set of fields are complete, such that no other field is needed to define the
 102  *  valid range of values for the fields that are represented
 103  * </ul><p>
 104  * <p>


 112  *  validity. It is able to implement plus/minus correctly, by wrapping around the day.
 113  * <li>{@code MonthDay}, the combination of month-of-year and day-of-month, does not implement
 114  *  this interface.  While the combination is contiguous, from days to months within years,
 115  *  the combination does not have sufficient information to define the valid range of values
 116  *  for day-of-month.  As such, it is unable to implement plus/minus correctly.
 117  * <li>The combination day-of-week and day-of-month ("Friday the 13th") should not implement
 118  *  this interface. It does not represent a contiguous set of fields, as days to weeks overlaps
 119  *  days to months.
 120  * </ul><p>
 121  *
 122  * @implSpec
 123  * This interface places no restrictions on the mutability of implementations,
 124  * however immutability is strongly recommended.
 125  * All implementations must be {@link Comparable}.
 126  *
 127  * @since 1.8
 128  */
 129 public interface Temporal extends TemporalAccessor {
 130 
 131     /**























 132      * Returns an adjusted object of the same type as this object with the adjustment made.
 133      * <p>
 134      * This adjusts this date-time according to the rules of the specified adjuster.
 135      * A simple adjuster might simply set the one of the fields, such as the year field.
 136      * A more complex adjuster might set the date to the last day of the month.
 137      * A selection of common adjustments is provided in {@link TemporalAdjuster}.
 138      * These include finding the "last day of the month" and "next Wednesday".
 139      * The adjuster is responsible for handling special cases, such as the varying
 140      * lengths of month and leap years.
 141      * <p>
 142      * Some example code indicating how and why this method is used:
 143      * <pre>
 144      *  date = date.with(Month.JULY);        // most key classes implement TemporalAdjuster
 145      *  date = date.with(lastDayOfMonth());  // static import from Adjusters
 146      *  date = date.with(next(WEDNESDAY));   // static import from Adjusters and DayOfWeek
 147      * </pre>
 148      *
 149      * @implSpec
 150      * Implementations must not alter either this object.
 151      * Instead, an adjusted copy of the original must be returned.


 335      * @param amountToSubtract  the amount of the specified unit to subtract, may be negative
 336      * @param unit  the unit of the period to subtract, not null
 337      * @return an object of the same type with the specified period subtracted, not null
 338      * @throws DateTimeException if the unit cannot be subtracted
 339      * @throws UnsupportedTemporalTypeException if the unit is not supported
 340      * @throws ArithmeticException if numeric overflow occurs
 341      */
 342     default Temporal minus(long amountToSubtract, TemporalUnit unit) {
 343         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
 344     }
 345 
 346     //-----------------------------------------------------------------------
 347     /**
 348      * Calculates the amount of time until another temporal in terms of the specified unit.
 349      * <p>
 350      * This calculates the amount of time between two temporal objects
 351      * of the same type in terms of a single {@code TemporalUnit}.
 352      * The start and end points are {@code this} and the specified temporal.
 353      * The result will be negative if the end is before the start.
 354      * For example, the period in hours between two temporal objects can be
 355      * calculated using {@code startTime.periodUntil(endTime, HOURS)}.
 356      * <p>
 357      * The calculation returns a whole number, representing the number of
 358      * complete units between the two temporals.
 359      * For example, the period in hours between the times 11:30 and 13:29
 360      * will only be one hour as it is one minute short of two hours.
 361      * <p>
 362      * There are two equivalent ways of using this method.
 363      * The first is to invoke this method directly.
 364      * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
 365      * <pre>
 366      *   // these two lines are equivalent
 367      *   temporal = start.periodUntil(end, unit);
 368      *   temporal = unit.between(start, end);
 369      * </pre>
 370      * The choice should be made based on which makes the code more readable.
 371      * <p>
 372      * For example, this method allows the number of days between two dates to
 373      * be calculated:
 374      * <pre>
 375      *  long daysBetween = start.periodUntil(end, DAYS);
 376      *  // or alternatively
 377      *  long daysBetween = DAYS.between(start, end);
 378      * </pre>
 379      *
 380      * @implSpec
 381      * Implementations must begin by checking to ensure that the input temporal
 382      * object is of the same observable type as the implementation.
 383      * They must then perform the calculation for all instances of {@link ChronoUnit}.
 384      * An {@code UnsupportedTemporalTypeException} must be thrown for {@code ChronoUnit}
 385      * instances that are unsupported.
 386      * <p>
 387      * If the unit is not a {@code ChronoUnit}, then the result of this method
 388      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
 389      * passing {@code this} as the first argument and the input temporal as
 390      * the second argument.
 391      * <p>
 392      * In summary, implementations must behave in a manner equivalent to this code:
 393      * <pre>
 394      *  // check input temporal is the same type as this class
 395      *  if (unit instanceof ChronoUnit) {
 396      *    // if unit is supported, then calculate and return result
 397      *    // else throw UnsupportedTemporalTypeException for unsupported units
 398      *  }
 399      *  return unit.between(this, endTemporal);
 400      * </pre>
 401      * <p>
 402      * Neither this object, nor the specified temporal, may be altered.

 403      *
 404      * @param endTemporal  the end temporal, of the same type as this object, not null
 405      * @param unit  the unit to measure the amount in, not null
 406      * @return the amount of time between this temporal object and the specified one
 407      *  in terms of the unit; positive if the specified object is later than this one,
 408      *  negative if it is earlier than this one
 409      * @throws DateTimeException if the amount cannot be calculated
 410      * @throws UnsupportedTemporalTypeException if the unit is not supported
 411      * @throws ArithmeticException if numeric overflow occurs
 412      */
 413     long periodUntil(Temporal endTemporal, TemporalUnit unit);
 414 
 415 }


  45  *
  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 
  66 /**
  67  * Framework-level interface defining read-write access to a temporal object,
  68  * such as a date, time, offset or some combination of these.
  69  * <p>
  70  * This is the base interface type for date, time and offset objects that
  71  * are complete enough to be manipulated using plus and minus.
  72  * It is implemented by those classes that can provide and manipulate information
  73  * as {@linkplain TemporalField fields} or {@linkplain TemporalQuery queries}.
  74  * See {@link TemporalAccessor} for the read-only version of this interface.
  75  * <p>
  76  * Most date and time information can be represented as a number.
  77  * These are modeled using {@code TemporalField} with the number held using
  78  * a {@code long} to handle large values. Year, month and day-of-month are
  79  * simple examples of fields, but they also include instant and offsets.
  80  * See {@link ChronoField} for the standard set of fields.
  81  * <p>
  82  * Two pieces of date/time information cannot be represented by numbers,
  83  * the {@linkplain java.time.chrono.Chronology chronology} and the
  84  * {@linkplain java.time.ZoneId time-zone}.
  85  * These can be accessed via {@link #query(TemporalQuery) queries} using
  86  * the static methods defined on {@link TemporalQuery}.
  87  * <p>
  88  * This interface is a framework-level interface that should not be widely
  89  * used in application code. Instead, applications should create and pass
  90  * around instances of concrete types, such as {@code LocalDate}.
  91  * There are many reasons for this, part of which is that implementations
  92  * of this interface may be in calendar systems other than ISO.
  93  * See {@link java.time.chrono.ChronoLocalDate} for a fuller discussion of the issues.
  94  *
  95  * <h3>When to implement</h3>
  96  * <p>
  97  * A class should implement this interface if it meets three criteria:
  98  * <p><ul>
  99  * <li>it provides access to date/time/offset information, as per {@code TemporalAccessor}
 100  * <li>the set of fields are contiguous from the largest to the smallest
 101  * <li>the set of fields are complete, such that no other field is needed to define the
 102  *  valid range of values for the fields that are represented
 103  * </ul><p>
 104  * <p>


 112  *  validity. It is able to implement plus/minus correctly, by wrapping around the day.
 113  * <li>{@code MonthDay}, the combination of month-of-year and day-of-month, does not implement
 114  *  this interface.  While the combination is contiguous, from days to months within years,
 115  *  the combination does not have sufficient information to define the valid range of values
 116  *  for day-of-month.  As such, it is unable to implement plus/minus correctly.
 117  * <li>The combination day-of-week and day-of-month ("Friday the 13th") should not implement
 118  *  this interface. It does not represent a contiguous set of fields, as days to weeks overlaps
 119  *  days to months.
 120  * </ul><p>
 121  *
 122  * @implSpec
 123  * This interface places no restrictions on the mutability of implementations,
 124  * however immutability is strongly recommended.
 125  * All implementations must be {@link Comparable}.
 126  *
 127  * @since 1.8
 128  */
 129 public interface Temporal extends TemporalAccessor {
 130 
 131     /**
 132      * Checks if the specified unit is supported.
 133      * <p>
 134      * This checks if the specified unit can be added to, or subtracted from, this date-time.
 135      * If false, then calling the {@link #plus(long, TemporalUnit)} and
 136      * {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
 137      *
 138      * @implSpec
 139      * Implementations must check and handle all units defined in {@link ChronoUnit}.
 140      * If the unit is supported, then true must be returned, otherwise false must be returned.
 141      * <p>
 142      * If the field is not a {@code ChronoUnit}, then the result of this method
 143      * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
 144      * passing {@code this} as the argument.
 145      * <p>
 146      * Implementations must ensure that no observable state is altered when this
 147      * read-only method is invoked.
 148      *
 149      * @param unit  the unit to check, null returns false
 150      * @return true if the unit can be added/subtracted, false if not
 151      */
 152     boolean isSupported(TemporalUnit unit);
 153 
 154     /**
 155      * Returns an adjusted object of the same type as this object with the adjustment made.
 156      * <p>
 157      * This adjusts this date-time according to the rules of the specified adjuster.
 158      * A simple adjuster might simply set the one of the fields, such as the year field.
 159      * A more complex adjuster might set the date to the last day of the month.
 160      * A selection of common adjustments is provided in {@link TemporalAdjuster}.
 161      * These include finding the "last day of the month" and "next Wednesday".
 162      * The adjuster is responsible for handling special cases, such as the varying
 163      * lengths of month and leap years.
 164      * <p>
 165      * Some example code indicating how and why this method is used:
 166      * <pre>
 167      *  date = date.with(Month.JULY);        // most key classes implement TemporalAdjuster
 168      *  date = date.with(lastDayOfMonth());  // static import from Adjusters
 169      *  date = date.with(next(WEDNESDAY));   // static import from Adjusters and DayOfWeek
 170      * </pre>
 171      *
 172      * @implSpec
 173      * Implementations must not alter either this object.
 174      * Instead, an adjusted copy of the original must be returned.


 358      * @param amountToSubtract  the amount of the specified unit to subtract, may be negative
 359      * @param unit  the unit of the period to subtract, not null
 360      * @return an object of the same type with the specified period subtracted, not null
 361      * @throws DateTimeException if the unit cannot be subtracted
 362      * @throws UnsupportedTemporalTypeException if the unit is not supported
 363      * @throws ArithmeticException if numeric overflow occurs
 364      */
 365     default Temporal minus(long amountToSubtract, TemporalUnit unit) {
 366         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
 367     }
 368 
 369     //-----------------------------------------------------------------------
 370     /**
 371      * Calculates the amount of time until another temporal in terms of the specified unit.
 372      * <p>
 373      * This calculates the amount of time between two temporal objects
 374      * of the same type in terms of a single {@code TemporalUnit}.
 375      * The start and end points are {@code this} and the specified temporal.
 376      * The result will be negative if the end is before the start.
 377      * For example, the period in hours between two temporal objects can be
 378      * calculated using {@code startTime.until(endTime, HOURS)}.
 379      * <p>
 380      * The calculation returns a whole number, representing the number of
 381      * complete units between the two temporals.
 382      * For example, the period in hours between the times 11:30 and 13:29
 383      * will only be one hour as it is one minute short of two hours.
 384      * <p>
 385      * There are two equivalent ways of using this method.
 386      * The first is to invoke this method directly.
 387      * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
 388      * <pre>
 389      *   // these two lines are equivalent
 390      *   temporal = start.until(end, unit);
 391      *   temporal = unit.between(start, end);
 392      * </pre>
 393      * The choice should be made based on which makes the code more readable.
 394      * <p>
 395      * For example, this method allows the number of days between two dates to
 396      * be calculated:
 397      * <pre>
 398      *  long daysBetween = start.until(end, DAYS);
 399      *  // or alternatively
 400      *  long daysBetween = DAYS.between(start, end);
 401      * </pre>
 402      *
 403      * @implSpec
 404      * Implementations must begin by checking to ensure that the input temporal
 405      * object is of the same observable type as the implementation.
 406      * They must then perform the calculation for all instances of {@link ChronoUnit}.
 407      * An {@code UnsupportedTemporalTypeException} must be thrown for {@code ChronoUnit}
 408      * instances that are unsupported.
 409      * <p>
 410      * If the unit is not a {@code ChronoUnit}, then the result of this method
 411      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
 412      * passing {@code this} as the first argument and the input temporal as
 413      * the second argument.
 414      * <p>
 415      * In summary, implementations must behave in a manner equivalent to this code:
 416      * <pre>
 417      *  // check input temporal is the same type as this class
 418      *  if (unit instanceof ChronoUnit) {
 419      *    // if unit is supported, then calculate and return result
 420      *    // else throw UnsupportedTemporalTypeException for unsupported units
 421      *  }
 422      *  return unit.between(this, endTemporal);
 423      * </pre>
 424      * <p>
 425      * Implementations must ensure that no observable state is altered when this
 426      * read-only method is invoked.
 427      *
 428      * @param endTemporal  the end temporal, of the same type as this object, not null
 429      * @param unit  the unit to measure the amount in, not null
 430      * @return the amount of time between this temporal object and the specified one
 431      *  in terms of the unit; positive if the specified object is later than this one,
 432      *  negative if it is earlier than this one
 433      * @throws DateTimeException if the amount cannot be calculated
 434      * @throws UnsupportedTemporalTypeException if the unit is not supported
 435      * @throws ArithmeticException if numeric overflow occurs
 436      */
 437     long until(Temporal endTemporal, TemporalUnit unit);
 438 
 439 }