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 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> 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 * @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. 175 * This provides equivalent, safe behavior for immutable and mutable implementations. 176 * <p> 177 * The default implementation must behave equivalent to this code: 178 * <pre> 179 * return adjuster.adjustInto(this); 180 * </pre> 181 * 182 * @param adjuster the adjuster to use, not null 183 * @return an object of the same type with the specified adjustment made, not null 184 * @throws DateTimeException if unable to make the adjustment 185 * @throws ArithmeticException if numeric overflow occurs 186 */ 187 default Temporal with(TemporalAdjuster adjuster) { 188 return adjuster.adjustInto(this); 189 } 190 191 /** 192 * Returns an object of the same type as this object with the specified field altered. 193 * <p> 194 * This returns a new object based on this one with the value for the specified field changed. 195 * For example, on a {@code LocalDate}, this could be used to set the year, month or day-of-month. 196 * The returned object will have the same observable type as this object. 197 * <p> 198 * In some cases, changing a field is not fully defined. For example, if the target object is 199 * a date representing the 31st January, then changing the month to February would be unclear. 200 * In cases like this, the field is responsible for resolving the result. Typically it will choose 201 * the previous valid date, which would be the last valid day of February in this example. 202 * 203 * @implSpec 204 * Implementations must check and handle all fields defined in {@link ChronoField}. 205 * If the field is supported, then the adjustment must be performed. 206 * If unsupported, then an {@code UnsupportedTemporalTypeException} must be thrown. 207 * <p> 208 * If the field is not a {@code ChronoField}, then the result of this method 209 * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)} 210 * passing {@code this} as the first argument. 211 * <p> 212 * Implementations must not alter either this object or the specified temporal object. 213 * Instead, an adjusted copy of the original must be returned. 214 * This provides equivalent, safe behavior for immutable and mutable implementations. 215 * 216 * @param field the field to set in the result, not null 217 * @param newValue the new value of the field in the result 218 * @return an object of the same type with the specified field set, not null 219 * @throws DateTimeException if the field cannot be set 220 * @throws UnsupportedTemporalTypeException if the field is not supported 221 * @throws ArithmeticException if numeric overflow occurs 222 */ 223 Temporal with(TemporalField field, long newValue); 224 225 //----------------------------------------------------------------------- 226 /** 227 * Returns an object of the same type as this object with an amount added. 228 * <p> 229 * This adjusts this temporal, adding according to the rules of the specified amount. 230 * The amount is typically a {@link java.time.Period} but may be any other type implementing 231 * the {@link TemporalAmount} interface, such as {@link java.time.Duration}. 232 * <p> 233 * Some example code indicating how and why this method is used: 234 * <pre> 235 * date = date.plus(period); // add a Period instance 236 * date = date.plus(duration); // add a Duration instance 237 * date = date.plus(workingDays(6)); // example user-written workingDays method 238 * </pre> 239 * <p> 240 * Note that calling {@code plus} followed by {@code minus} is not guaranteed to 241 * return the same date-time. 242 * 243 * @implSpec 244 * Implementations must not alter either this object. 245 * Instead, an adjusted copy of the original must be returned. 246 * This provides equivalent, safe behavior for immutable and mutable implementations. 247 * <p> 248 * The default implementation must behave equivalent to this code: 249 * <pre> 250 * return amount.addTo(this); 251 * </pre> 252 * 253 * @param amount the amount to add, not null 254 * @return an object of the same type with the specified adjustment made, not null 255 * @throws DateTimeException if the addition cannot be made 256 * @throws ArithmeticException if numeric overflow occurs 257 */ 258 default Temporal plus(TemporalAmount amount) { 259 return amount.addTo(this); 260 } 261 262 /** 263 * Returns an object of the same type as this object with the specified period added. 264 * <p> 265 * This method returns a new object based on this one with the specified period added. 266 * For example, on a {@code LocalDate}, this could be used to add a number of years, months or days. 267 * The returned object will have the same observable type as this object. 268 * <p> 269 * In some cases, changing a field is not fully defined. For example, if the target object is 270 * a date representing the 31st January, then adding one month would be unclear. 271 * In cases like this, the field is responsible for resolving the result. Typically it will choose 272 * the previous valid date, which would be the last valid day of February in this example. 273 * 274 * @implSpec 275 * Implementations must check and handle all units defined in {@link ChronoUnit}. 276 * If the unit is supported, then the addition must be performed. 277 * If unsupported, then an {@code UnsupportedTemporalTypeException} must be thrown. 278 * <p> 279 * If the unit is not a {@code ChronoUnit}, then the result of this method 280 * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)} 281 * passing {@code this} as the first argument. 282 * <p> 283 * Implementations must not alter either this object or the specified temporal object. 284 * Instead, an adjusted copy of the original must be returned. 285 * This provides equivalent, safe behavior for immutable and mutable implementations. 286 * 287 * @param amountToAdd the amount of the specified unit to add, may be negative 288 * @param unit the unit of the period to add, not null 289 * @return an object of the same type with the specified period added, not null 290 * @throws DateTimeException if the unit cannot be added 291 * @throws UnsupportedTemporalTypeException if the unit is not supported 292 * @throws ArithmeticException if numeric overflow occurs 293 */ 294 Temporal plus(long amountToAdd, TemporalUnit unit); 295 296 //----------------------------------------------------------------------- 297 /** 298 * Returns an object of the same type as this object with an amount subtracted. 299 * <p> 300 * This adjusts this temporal, subtracting according to the rules of the specified amount. 301 * The amount is typically a {@link java.time.Period} but may be any other type implementing 302 * the {@link TemporalAmount} interface, such as {@link java.time.Duration}. 303 * <p> 304 * Some example code indicating how and why this method is used: 305 * <pre> 306 * date = date.minus(period); // subtract a Period instance 307 * date = date.minus(duration); // subtract a Duration instance 308 * date = date.minus(workingDays(6)); // example user-written workingDays method 309 * </pre> 310 * <p> 311 * Note that calling {@code plus} followed by {@code minus} is not guaranteed to 312 * return the same date-time. 313 * 314 * @implSpec 315 * Implementations must not alter either this object. 316 * Instead, an adjusted copy of the original must be returned. 317 * This provides equivalent, safe behavior for immutable and mutable implementations. 318 * <p> 319 * The default implementation must behave equivalent to this code: 320 * <pre> 321 * return amount.subtractFrom(this); 322 * </pre> 323 * 324 * @param amount the amount to subtract, not null 325 * @return an object of the same type with the specified adjustment made, not null 326 * @throws DateTimeException if the subtraction cannot be made 327 * @throws ArithmeticException if numeric overflow occurs 328 */ 329 default Temporal minus(TemporalAmount amount) { 330 return amount.subtractFrom(this); 331 } 332 333 /** 334 * Returns an object of the same type as this object with the specified period subtracted. 335 * <p> 336 * This method returns a new object based on this one with the specified period subtracted. 337 * For example, on a {@code LocalDate}, this could be used to subtract a number of years, months or days. 338 * The returned object will have the same observable type as this object. 339 * <p> 340 * In some cases, changing a field is not fully defined. For example, if the target object is 341 * a date representing the 31st March, then subtracting one month would be unclear. 342 * In cases like this, the field is responsible for resolving the result. Typically it will choose 343 * the previous valid date, which would be the last valid day of February in this example. 344 * 345 * @implSpec 346 * Implementations must behave in a manor equivalent to the default method behavior. 347 * <p> 348 * Implementations must not alter either this object or the specified temporal object. 349 * Instead, an adjusted copy of the original must be returned. 350 * This provides equivalent, safe behavior for immutable and mutable implementations. 351 * <p> 352 * The default implementation must behave equivalent to this code: 353 * <pre> 354 * return (amountToSubtract == Long.MIN_VALUE ? 355 * plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); 356 * </pre> 357 * 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 }