1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file:
  31  *
  32  * Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
  33  *
  34  * All rights reserved.
  35  *
  36  * Redistribution and use in source and binary forms, with or without
  37  * modification, are permitted provided that the following conditions are met:
  38  *
  39  *  * Redistributions of source code must retain the above copyright notice,
  40  *    this list of conditions and the following disclaimer.
  41  *
  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  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 Queries}.
  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>
 105  * Four examples make this clear:
 106  * <p><ul>
 107  * <li>{@code LocalDate} implements this interface as it represents a set of fields
 108  *  that are contiguous from days to forever and require no external information to determine
 109  *  the validity of each date. It is therefore able to implement plus/minus correctly.
 110  * <li>{@code LocalTime} implements this interface as it represents a set of fields
 111  *  that are contiguous from nanos to within days and require no external information to determine
 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  * <h3>Specification for implementors</h3>
 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 Adjusters}.
 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      * <h3>Specification for implementors</h3>
 150      * Implementations must not alter either this object.
 151      * Instead, an adjusted copy of the original must be returned.
 152      * This provides equivalent, safe behavior for immutable and mutable implementations.
 153      * <p>
 154      * The default implementation must behave equivalent to this code:
 155      * <pre>
 156      *  return adjuster.adjustInto(this);
 157      * </pre>
 158      *
 159      * @param adjuster  the adjuster to use, not null
 160      * @return an object of the same type with the specified adjustment made, not null
 161      * @throws DateTimeException if unable to make the adjustment
 162      * @throws ArithmeticException if numeric overflow occurs
 163      */
 164     public default Temporal with(TemporalAdjuster adjuster) {
 165         return adjuster.adjustInto(this);
 166     }
 167 
 168     /**
 169      * Returns an object of the same type as this object with the specified field altered.
 170      * <p>
 171      * This returns a new object based on this one with the value for the specified field changed.
 172      * For example, on a {@code LocalDate}, this could be used to set the year, month or day-of-month.
 173      * The returned object will have the same observable type as this object.
 174      * <p>
 175      * In some cases, changing a field is not fully defined. For example, if the target object is
 176      * a date representing the 31st January, then changing the month to February would be unclear.
 177      * In cases like this, the field is responsible for resolving the result. Typically it will choose
 178      * the previous valid date, which would be the last valid day of February in this example.
 179      *
 180      * <h3>Specification for implementors</h3>
 181      * Implementations must check and handle all fields defined in {@link ChronoField}.
 182      * If the field is supported, then the adjustment must be performed.
 183      * If unsupported, then a {@code DateTimeException} must be thrown.
 184      * <p>
 185      * If the field is not a {@code ChronoField}, then the result of this method
 186      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
 187      * passing {@code this} as the first argument.
 188      * <p>
 189      * Implementations must not alter either this object or the specified temporal object.
 190      * Instead, an adjusted copy of the original must be returned.
 191      * This provides equivalent, safe behavior for immutable and mutable implementations.
 192      *
 193      * @param field  the field to set in the result, not null
 194      * @param newValue  the new value of the field in the result
 195      * @return an object of the same type with the specified field set, not null
 196      * @throws DateTimeException if the field cannot be set
 197      * @throws ArithmeticException if numeric overflow occurs
 198      */
 199     Temporal with(TemporalField field, long newValue);
 200 
 201     //-----------------------------------------------------------------------
 202     /**
 203      * Returns an object of the same type as this object with an amount added.
 204      * <p>
 205      * This adjusts this temporal, adding according to the rules of the specified amount.
 206      * The amount is typically a {@link java.time.Period} but may be any other type implementing
 207      * the {@link TemporalAmount} interface, such as {@link java.time.Duration}.
 208      * <p>
 209      * Some example code indicating how and why this method is used:
 210      * <pre>
 211      *  date = date.plus(period);                      // add a Period instance
 212      *  date = date.plus(duration);                    // add a Duration instance
 213      *  date = date.plus(MONTHS.between(start, end));  // static import of MONTHS field
 214      *  date = date.plus(workingDays(6));              // example user-written workingDays method
 215      * </pre>
 216      * <p>
 217      * Note that calling {@code plus} followed by {@code minus} is not guaranteed to
 218      * return the same date-time.
 219      *
 220      * <h3>Specification for implementors</h3>
 221      * Implementations must not alter either this object.
 222      * Instead, an adjusted copy of the original must be returned.
 223      * This provides equivalent, safe behavior for immutable and mutable implementations.
 224      * <p>
 225      * The default implementation must behave equivalent to this code:
 226      * <pre>
 227      *  return amount.addTo(this);
 228      * </pre>
 229      *
 230      * @param amount  the amount to add, not null
 231      * @return an object of the same type with the specified adjustment made, not null
 232      * @throws DateTimeException if the addition cannot be made
 233      * @throws ArithmeticException if numeric overflow occurs
 234      */
 235     public default Temporal plus(TemporalAmount amount) {
 236         return amount.addTo(this);
 237     }
 238 
 239     /**
 240      * Returns an object of the same type as this object with the specified period added.
 241      * <p>
 242      * This method returns a new object based on this one with the specified period added.
 243      * For example, on a {@code LocalDate}, this could be used to add a number of years, months or days.
 244      * The returned object will have the same observable type as this object.
 245      * <p>
 246      * In some cases, changing a field is not fully defined. For example, if the target object is
 247      * a date representing the 31st January, then adding one month would be unclear.
 248      * In cases like this, the field is responsible for resolving the result. Typically it will choose
 249      * the previous valid date, which would be the last valid day of February in this example.
 250      * <p>
 251      * If the implementation represents a date-time that has boundaries, such as {@code LocalTime},
 252      * then the permitted units must include the boundary unit, but no multiples of the boundary unit.
 253      * For example, {@code LocalTime} must accept {@code DAYS} but not {@code WEEKS} or {@code MONTHS}.
 254      *
 255      * <h3>Specification for implementors</h3>
 256      * Implementations must check and handle all units defined in {@link ChronoUnit}.
 257      * If the unit is supported, then the addition must be performed.
 258      * If unsupported, then a {@code DateTimeException} must be thrown.
 259      * <p>
 260      * If the unit is not a {@code ChronoUnit}, then the result of this method
 261      * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
 262      * passing {@code this} as the first argument.
 263      * <p>
 264      * Implementations must not alter either this object or the specified temporal object.
 265      * Instead, an adjusted copy of the original must be returned.
 266      * This provides equivalent, safe behavior for immutable and mutable implementations.
 267      *
 268      * @param amountToAdd  the amount of the specified unit to add, may be negative
 269      * @param unit  the unit of the period to add, not null
 270      * @return an object of the same type with the specified period added, not null
 271      * @throws DateTimeException if the unit cannot be added
 272      * @throws ArithmeticException if numeric overflow occurs
 273      */
 274     Temporal plus(long amountToAdd, TemporalUnit unit);
 275 
 276     //-----------------------------------------------------------------------
 277     /**
 278      * Returns an object of the same type as this object with an amount subtracted.
 279      * <p>
 280      * This adjusts this temporal, subtracting according to the rules of the specified amount.
 281      * The amount is typically a {@link java.time.Period} but may be any other type implementing
 282      * the {@link TemporalAmount} interface, such as {@link java.time.Duration}.
 283      * <p>
 284      * Some example code indicating how and why this method is used:
 285      * <pre>
 286      *  date = date.minus(period);                      // subtract a Period instance
 287      *  date = date.minus(duration);                    // subtract a Duration instance
 288      *  date = date.minus(MONTHS.between(start, end));  // static import of MONTHS field
 289      *  date = date.minus(workingDays(6));              // example user-written workingDays method
 290      * </pre>
 291      * <p>
 292      * Note that calling {@code plus} followed by {@code minus} is not guaranteed to
 293      * return the same date-time.
 294      *
 295      * <h3>Specification for implementors</h3>
 296      * Implementations must not alter either this object.
 297      * Instead, an adjusted copy of the original must be returned.
 298      * This provides equivalent, safe behavior for immutable and mutable implementations.
 299      * <p>
 300      * The default implementation must behave equivalent to this code:
 301      * <pre>
 302      *  return amount.subtractFrom(this);
 303      * </pre>
 304      *
 305      * @param amount  the amount to subtract, not null
 306      * @return an object of the same type with the specified adjustment made, not null
 307      * @throws DateTimeException if the subtraction cannot be made
 308      * @throws ArithmeticException if numeric overflow occurs
 309      */
 310     public default Temporal minus(TemporalAmount amount) {
 311         return amount.subtractFrom(this);
 312     }
 313 
 314     /**
 315      * Returns an object of the same type as this object with the specified period subtracted.
 316      * <p>
 317      * This method returns a new object based on this one with the specified period subtracted.
 318      * For example, on a {@code LocalDate}, this could be used to subtract a number of years, months or days.
 319      * The returned object will have the same observable type as this object.
 320      * <p>
 321      * In some cases, changing a field is not fully defined. For example, if the target object is
 322      * a date representing the 31st March, then subtracting one month would be unclear.
 323      * In cases like this, the field is responsible for resolving the result. Typically it will choose
 324      * the previous valid date, which would be the last valid day of February in this example.
 325      * <p>
 326      * If the implementation represents a date-time that has boundaries, such as {@code LocalTime},
 327      * then the permitted units must include the boundary unit, but no multiples of the boundary unit.
 328      * For example, {@code LocalTime} must accept {@code DAYS} but not {@code WEEKS} or {@code MONTHS}.
 329      *
 330      * <h3>Specification for implementors</h3>
 331      * Implementations must behave in a manor equivalent to the default method behavior.
 332      * <p>
 333      * Implementations must not alter either this object or the specified temporal object.
 334      * Instead, an adjusted copy of the original must be returned.
 335      * This provides equivalent, safe behavior for immutable and mutable implementations.
 336      * <p>
 337      * The default implementation must behave equivalent to this code:
 338      * <pre>
 339      *  return (amountToSubtract == Long.MIN_VALUE ?
 340      *      plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
 341      * </pre>
 342      *
 343      * @param amountToSubtract  the amount of the specified unit to subtract, may be negative
 344      * @param unit  the unit of the period to subtract, not null
 345      * @return an object of the same type with the specified period subtracted, not null
 346      * @throws DateTimeException if the unit cannot be subtracted
 347      * @throws ArithmeticException if numeric overflow occurs
 348      */
 349     public default Temporal minus(long amountToSubtract, TemporalUnit unit) {
 350         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
 351     }
 352 
 353     //-----------------------------------------------------------------------
 354     /**
 355      * Calculates the period between this temporal and another temporal in
 356      * terms of the specified unit.
 357      * <p>
 358      * This calculates the period between two temporals in terms of a single unit.
 359      * The start and end points are {@code this} and the specified temporal.
 360      * The result will be negative if the end is before the start.
 361      * For example, the period in hours between two temporal objects can be
 362      * calculated using {@code startTime.periodUntil(endTime, HOURS)}.
 363      * <p>
 364      * The calculation returns a whole number, representing the number of
 365      * complete units between the two temporals.
 366      * For example, the period in hours between the times 11:30 and 13:29
 367      * will only be one hour as it is one minute short of two hours.
 368      * <p>
 369      * There are two equivalent ways of using this method.
 370      * The first is to invoke this method directly.
 371      * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
 372      * <pre>
 373      *   // these two lines are equivalent
 374      *   temporal = start.periodUntil(end, unit);
 375      *   temporal = unit.between(start, end);
 376      * </pre>
 377      * The choice should be made based on which makes the code more readable.
 378      * <p>
 379      * For example, this method allows the number of days between two dates to
 380      * be calculated:
 381      * <pre>
 382      *  long daysBetween = start.periodUntil(end, DAYS);
 383      *  // or alternatively
 384      *  long daysBetween = DAYS.between(start, end);
 385      * </pre>
 386      *
 387      * <h3>Specification for implementors</h3>
 388      * Implementations must begin by checking to ensure that the input temporal
 389      * object is of the same observable type as the implementation.
 390      * They must then perform the calculation for all instances of {@link ChronoUnit}.
 391      * A {@code DateTimeException} must be thrown for {@code ChronoUnit}
 392      * instances that are unsupported.
 393      * <p>
 394      * If the unit is not a {@code ChronoUnit}, then the result of this method
 395      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
 396      * passing {@code this} as the first argument and the input temporal as
 397      * the second argument.
 398      * <p>
 399      * In summary, implementations must behave in a manner equivalent to this code:
 400      * <pre>
 401      *  // check input temporal is the same type as this class
 402      *  if (unit instanceof ChronoUnit) {
 403      *    // if unit is supported, then calculate and return result
 404      *    // else throw DateTimeException for unsupported units
 405      *  }
 406      *  return unit.between(this, endTemporal);
 407      * </pre>
 408      * <p>
 409      * Neither this object, nor the specified temporal, may be altered.
 410      *
 411      * @param endTemporal  the end temporal, of the same type as this object, not null
 412      * @param unit  the unit to measure the period in, not null
 413      * @return the period between this temporal object and the specified one in terms of
 414      *  the unit; positive if the specified object is later than this one, negative if
 415      *  it is earlier than this one
 416      * @throws DateTimeException if the period cannot be calculated
 417      * @throws ArithmeticException if numeric overflow occurs
 418      */
 419     long periodUntil(Temporal endTemporal, TemporalUnit unit);
 420 
 421 }