• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2012, 2015, 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 
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  * <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>
104  * <p>
105  * Four examples make this clear:
106  * <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>
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      */
isSupported(TemporalUnit unit)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
161      * {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}.
162      * These include finding the "last day of the month" and "next Wednesday".
163      * The adjuster is responsible for handling special cases, such as the varying
164      * lengths of month and leap years.
165      * <p>
166      * Some example code indicating how and why this method is used:
167      * <pre>
168      *  date = date.with(Month.JULY);        // most key classes implement TemporalAdjuster
169      *  date = date.with(lastDayOfMonth());  // static import from Adjusters
170      *  date = date.with(next(WEDNESDAY));   // static import from Adjusters and DayOfWeek
171      * </pre>
172      *
173      * @implSpec
174      * <p>
175      * Implementations must not alter either this object or the specified temporal object.
176      * Instead, an adjusted copy of the original must be returned.
177      * This provides equivalent, safe behavior for immutable and mutable implementations.
178      * <p>
179      * The default implementation must behave equivalent to this code:
180      * <pre>
181      *  return adjuster.adjustInto(this);
182      * </pre>
183      *
184      * @param adjuster  the adjuster to use, not null
185      * @return an object of the same type with the specified adjustment made, not null
186      * @throws DateTimeException if unable to make the adjustment
187      * @throws ArithmeticException if numeric overflow occurs
188      */
with(TemporalAdjuster adjuster)189     default Temporal with(TemporalAdjuster adjuster) {
190         return adjuster.adjustInto(this);
191     }
192 
193     /**
194      * Returns an object of the same type as this object with the specified field altered.
195      * <p>
196      * This returns a new object based on this one with the value for the specified field changed.
197      * For example, on a {@code LocalDate}, this could be used to set the year, month or day-of-month.
198      * The returned object will have the same observable type as this object.
199      * <p>
200      * In some cases, changing a field is not fully defined. For example, if the target object is
201      * a date representing the 31st January, then changing the month to February would be unclear.
202      * In cases like this, the field is responsible for resolving the result. Typically it will choose
203      * the previous valid date, which would be the last valid day of February in this example.
204      *
205      * @implSpec
206      * Implementations must check and handle all fields defined in {@link ChronoField}.
207      * If the field is supported, then the adjustment must be performed.
208      * If unsupported, then an {@code UnsupportedTemporalTypeException} must be thrown.
209      * <p>
210      * If the field is not a {@code ChronoField}, then the result of this method
211      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
212      * passing {@code this} as the first argument.
213      * <p>
214      * Implementations must not alter this object.
215      * Instead, an adjusted copy of the original must be returned.
216      * This provides equivalent, safe behavior for immutable and mutable implementations.
217      *
218      * @param field  the field to set in the result, not null
219      * @param newValue  the new value of the field in the result
220      * @return an object of the same type with the specified field set, not null
221      * @throws DateTimeException if the field cannot be set
222      * @throws UnsupportedTemporalTypeException if the field is not supported
223      * @throws ArithmeticException if numeric overflow occurs
224      */
with(TemporalField field, long newValue)225     Temporal with(TemporalField field, long newValue);
226 
227     //-----------------------------------------------------------------------
228     /**
229      * Returns an object of the same type as this object with an amount added.
230      * <p>
231      * This adjusts this temporal, adding according to the rules of the specified amount.
232      * The amount is typically a {@link java.time.Period} but may be any other type implementing
233      * the {@link TemporalAmount} interface, such as {@link java.time.Duration}.
234      * <p>
235      * Some example code indicating how and why this method is used:
236      * <pre>
237      *  date = date.plus(period);                // add a Period instance
238      *  date = date.plus(duration);              // add a Duration instance
239      *  date = date.plus(workingDays(6));        // example user-written workingDays method
240      * </pre>
241      * <p>
242      * Note that calling {@code plus} followed by {@code minus} is not guaranteed to
243      * return the same date-time.
244      *
245      * @implSpec
246      * <p>
247      * Implementations must not alter either this object or the specified temporal object.
248      * Instead, an adjusted copy of the original must be returned.
249      * This provides equivalent, safe behavior for immutable and mutable implementations.
250      * <p>
251      * The default implementation must behave equivalent to this code:
252      * <pre>
253      *  return amount.addTo(this);
254      * </pre>
255      *
256      * @param amount  the amount to add, not null
257      * @return an object of the same type with the specified adjustment made, not null
258      * @throws DateTimeException if the addition cannot be made
259      * @throws ArithmeticException if numeric overflow occurs
260      */
plus(TemporalAmount amount)261     default Temporal plus(TemporalAmount amount) {
262         return amount.addTo(this);
263     }
264 
265     /**
266      * Returns an object of the same type as this object with the specified period added.
267      * <p>
268      * This method returns a new object based on this one with the specified period added.
269      * For example, on a {@code LocalDate}, this could be used to add a number of years, months or days.
270      * The returned object will have the same observable type as this object.
271      * <p>
272      * In some cases, changing a field is not fully defined. For example, if the target object is
273      * a date representing the 31st January, then adding one month would be unclear.
274      * In cases like this, the field is responsible for resolving the result. Typically it will choose
275      * the previous valid date, which would be the last valid day of February in this example.
276      *
277      * @implSpec
278      * Implementations must check and handle all units defined in {@link ChronoUnit}.
279      * If the unit is supported, then the addition must be performed.
280      * If unsupported, then an {@code UnsupportedTemporalTypeException} must be thrown.
281      * <p>
282      * If the unit is not a {@code ChronoUnit}, then the result of this method
283      * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
284      * passing {@code this} as the first argument.
285      * <p>
286      * Implementations must not alter this object.
287      * Instead, an adjusted copy of the original must be returned.
288      * This provides equivalent, safe behavior for immutable and mutable implementations.
289      *
290      * @param amountToAdd  the amount of the specified unit to add, may be negative
291      * @param unit  the unit of the amount to add, not null
292      * @return an object of the same type with the specified period added, not null
293      * @throws DateTimeException if the unit cannot be added
294      * @throws UnsupportedTemporalTypeException if the unit is not supported
295      * @throws ArithmeticException if numeric overflow occurs
296      */
plus(long amountToAdd, TemporalUnit unit)297     Temporal plus(long amountToAdd, TemporalUnit unit);
298 
299     //-----------------------------------------------------------------------
300     /**
301      * Returns an object of the same type as this object with an amount subtracted.
302      * <p>
303      * This adjusts this temporal, subtracting according to the rules of the specified amount.
304      * The amount is typically a {@link java.time.Period} but may be any other type implementing
305      * the {@link TemporalAmount} interface, such as {@link java.time.Duration}.
306      * <p>
307      * Some example code indicating how and why this method is used:
308      * <pre>
309      *  date = date.minus(period);               // subtract a Period instance
310      *  date = date.minus(duration);             // subtract a Duration instance
311      *  date = date.minus(workingDays(6));       // example user-written workingDays method
312      * </pre>
313      * <p>
314      * Note that calling {@code plus} followed by {@code minus} is not guaranteed to
315      * return the same date-time.
316      *
317      * @implSpec
318      * <p>
319      * Implementations must not alter either this object or the specified temporal object.
320      * Instead, an adjusted copy of the original must be returned.
321      * This provides equivalent, safe behavior for immutable and mutable implementations.
322      * <p>
323      * The default implementation must behave equivalent to this code:
324      * <pre>
325      *  return amount.subtractFrom(this);
326      * </pre>
327      *
328      * @param amount  the amount to subtract, not null
329      * @return an object of the same type with the specified adjustment made, not null
330      * @throws DateTimeException if the subtraction cannot be made
331      * @throws ArithmeticException if numeric overflow occurs
332      */
minus(TemporalAmount amount)333     default Temporal minus(TemporalAmount amount) {
334         return amount.subtractFrom(this);
335     }
336 
337     /**
338      * Returns an object of the same type as this object with the specified period subtracted.
339      * <p>
340      * This method returns a new object based on this one with the specified period subtracted.
341      * For example, on a {@code LocalDate}, this could be used to subtract a number of years, months or days.
342      * The returned object will have the same observable type as this object.
343      * <p>
344      * In some cases, changing a field is not fully defined. For example, if the target object is
345      * a date representing the 31st March, then subtracting one month would be unclear.
346      * In cases like this, the field is responsible for resolving the result. Typically it will choose
347      * the previous valid date, which would be the last valid day of February in this example.
348      *
349      * @implSpec
350      * Implementations must behave in a manor equivalent to the default method behavior.
351      * <p>
352      * Implementations must not alter this object.
353      * Instead, an adjusted copy of the original must be returned.
354      * This provides equivalent, safe behavior for immutable and mutable implementations.
355      * <p>
356      * The default implementation must behave equivalent to this code:
357      * <pre>
358      *  return (amountToSubtract == Long.MIN_VALUE ?
359      *      plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
360      * </pre>
361      *
362      * @param amountToSubtract  the amount of the specified unit to subtract, may be negative
363      * @param unit  the unit of the amount to subtract, not null
364      * @return an object of the same type with the specified period subtracted, not null
365      * @throws DateTimeException if the unit cannot be subtracted
366      * @throws UnsupportedTemporalTypeException if the unit is not supported
367      * @throws ArithmeticException if numeric overflow occurs
368      */
minus(long amountToSubtract, TemporalUnit unit)369     default Temporal minus(long amountToSubtract, TemporalUnit unit) {
370         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
371     }
372 
373     //-----------------------------------------------------------------------
374     /**
375      * Calculates the amount of time until another temporal in terms of the specified unit.
376      * <p>
377      * This calculates the amount of time between two temporal objects
378      * in terms of a single {@code TemporalUnit}.
379      * The start and end points are {@code this} and the specified temporal.
380      * The end point is converted to be of the same type as the start point if different.
381      * The result will be negative if the end is before the start.
382      * For example, the amount in hours between two temporal objects can be
383      * calculated using {@code startTime.until(endTime, HOURS)}.
384      * <p>
385      * The calculation returns a whole number, representing the number of
386      * complete units between the two temporals.
387      * For example, the amount in hours between the times 11:30 and 13:29
388      * will only be one hour as it is one minute short of two hours.
389      * <p>
390      * There are two equivalent ways of using this method.
391      * The first is to invoke this method directly.
392      * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
393      * <pre>
394      *   // these two lines are equivalent
395      *   temporal = start.until(end, unit);
396      *   temporal = unit.between(start, end);
397      * </pre>
398      * The choice should be made based on which makes the code more readable.
399      * <p>
400      * For example, this method allows the number of days between two dates to
401      * be calculated:
402      * <pre>
403      *  long daysBetween = start.until(end, DAYS);
404      *  // or alternatively
405      *  long daysBetween = DAYS.between(start, end);
406      * </pre>
407      *
408      * @implSpec
409      * Implementations must begin by checking to ensure that the input temporal
410      * object is of the same observable type as the implementation.
411      * They must then perform the calculation for all instances of {@link ChronoUnit}.
412      * An {@code UnsupportedTemporalTypeException} must be thrown for {@code ChronoUnit}
413      * instances that are unsupported.
414      * <p>
415      * If the unit is not a {@code ChronoUnit}, then the result of this method
416      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
417      * passing {@code this} as the first argument and the converted input temporal as
418      * the second argument.
419      * <p>
420      * In summary, implementations must behave in a manner equivalent to this pseudo-code:
421      * <pre>
422      *  // convert the end temporal to the same type as this class
423      *  if (unit instanceof ChronoUnit) {
424      *    // if unit is supported, then calculate and return result
425      *    // else throw UnsupportedTemporalTypeException for unsupported units
426      *  }
427      *  return unit.between(this, convertedEndTemporal);
428      * </pre>
429      * <p>
430      * Note that the unit's {@code between} method must only be invoked if the
431      * two temporal objects have exactly the same type evaluated by {@code getClass()}.
432      * <p>
433      * Implementations must ensure that no observable state is altered when this
434      * read-only method is invoked.
435      *
436      * @param endExclusive  the end temporal, exclusive, converted to be of the
437      *  same type as this object, not null
438      * @param unit  the unit to measure the amount in, not null
439      * @return the amount of time between this temporal object and the specified one
440      *  in terms of the unit; positive if the specified object is later than this one,
441      *  negative if it is earlier than this one
442      * @throws DateTimeException if the amount cannot be calculated, or the end
443      *  temporal cannot be converted to the same type as this temporal
444      * @throws UnsupportedTemporalTypeException if the unit is not supported
445      * @throws ArithmeticException if numeric overflow occurs
446      */
until(Temporal endExclusive, TemporalUnit unit)447     long until(Temporal endExclusive, TemporalUnit unit);
448 
449 }
450