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) 2007-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; 63 64 import static java.time.LocalTime.SECONDS_PER_DAY; 65 import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH; 66 import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR; 67 import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH; 68 import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR; 69 import static java.time.temporal.ChronoField.DAY_OF_MONTH; 70 import static java.time.temporal.ChronoField.DAY_OF_YEAR; 71 import static java.time.temporal.ChronoField.EPOCH_DAY; 72 import static java.time.temporal.ChronoField.ERA; 73 import static java.time.temporal.ChronoField.MONTH_OF_YEAR; 74 import static java.time.temporal.ChronoField.PROLEPTIC_MONTH; 75 import static java.time.temporal.ChronoField.YEAR; 76 77 import java.io.DataInput; 78 import java.io.DataOutput; 79 import java.io.IOException; 80 import java.io.InvalidObjectException; 81 import java.io.ObjectInputStream; 82 import java.io.Serializable; 83 import java.time.chrono.ChronoLocalDate; 84 import java.time.chrono.IsoEra; 85 import java.time.chrono.IsoChronology; 86 import java.time.format.DateTimeFormatter; 87 import java.time.format.DateTimeParseException; 88 import java.time.temporal.ChronoField; 89 import java.time.temporal.ChronoUnit; 90 import java.time.temporal.Temporal; 91 import java.time.temporal.TemporalAccessor; 92 import java.time.temporal.TemporalAdjuster; 93 import java.time.temporal.TemporalAmount; 94 import java.time.temporal.TemporalField; 95 import java.time.temporal.TemporalQueries; 96 import java.time.temporal.TemporalQuery; 97 import java.time.temporal.TemporalUnit; 98 import java.time.temporal.UnsupportedTemporalTypeException; 99 import java.time.temporal.ValueRange; 100 import java.time.zone.ZoneOffsetTransition; 101 import java.time.zone.ZoneRules; 102 import java.util.Objects; 103 104 /** 105 * A date without a time-zone in the ISO-8601 calendar system, 106 * such as {@code 2007-12-03}. 107 * <p> 108 * {@code LocalDate} is an immutable date-time object that represents a date, 109 * often viewed as year-month-day. Other date fields, such as day-of-year, 110 * day-of-week and week-of-year, can also be accessed. 111 * For example, the value "2nd October 2007" can be stored in a {@code LocalDate}. 112 * <p> 113 * This class does not store or represent a time or time-zone. 114 * Instead, it is a description of the date, as used for birthdays. 115 * It cannot represent an instant on the time-line without additional information 116 * such as an offset or time-zone. 117 * <p> 118 * The ISO-8601 calendar system is the modern civil calendar system used today 119 * in most of the world. It is equivalent to the proleptic Gregorian calendar 120 * system, in which today's rules for leap years are applied for all time. 121 * For most applications written today, the ISO-8601 rules are entirely suitable. 122 * However, any application that makes use of historical dates, and requires them 123 * to be accurate will find the ISO-8601 approach unsuitable. 124 * 125 * <p> 126 * This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a> 127 * class; use of identity-sensitive operations (including reference equality 128 * ({@code ==}), identity hash code, or synchronization) on instances of 129 * {@code LocalDate} may have unpredictable results and should be avoided. 130 * The {@code equals} method should be used for comparisons. 131 * 132 * @implSpec 133 * This class is immutable and thread-safe. 134 * 135 * @since 1.8 136 */ 137 public final class LocalDate 138 implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable { 139 140 /** 141 * The minimum supported {@code LocalDate}, '-999999999-01-01'. 142 * This could be used by an application as a "far past" date. 143 */ 144 public static final LocalDate MIN = LocalDate.of(Year.MIN_VALUE, 1, 1); 145 /** 146 * The maximum supported {@code LocalDate}, '+999999999-12-31'. 147 * This could be used by an application as a "far future" date. 148 */ 149 public static final LocalDate MAX = LocalDate.of(Year.MAX_VALUE, 12, 31); 150 151 /** 152 * Serialization version. 153 */ 154 private static final long serialVersionUID = 2942565459149668126L; 155 /** 156 * The number of days in a 400 year cycle. 157 */ 158 private static final int DAYS_PER_CYCLE = 146097; 159 /** 160 * The number of days from year zero to year 1970. 161 * There are five 400 year cycles from year zero to 2000. 162 * There are 7 leap years from 1970 to 2000. 163 */ 164 static final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L); 165 166 /** 167 * The year. 168 */ 169 private final int year; 170 /** 171 * The month-of-year. 172 */ 173 private final short month; 174 /** 175 * The day-of-month. 176 */ 177 private final short day; 178 179 //----------------------------------------------------------------------- 180 /** 181 * Obtains the current date from the system clock in the default time-zone. 182 * <p> 183 * This will query the {@link Clock#systemDefaultZone() system clock} in the default 184 * time-zone to obtain the current date. 185 * <p> 186 * Using this method will prevent the ability to use an alternate clock for testing 187 * because the clock is hard-coded. 188 * 189 * @return the current date using the system clock and default time-zone, not null 190 */ 191 public static LocalDate now() { 192 return now(Clock.systemDefaultZone()); 193 } 194 195 /** 196 * Obtains the current date from the system clock in the specified time-zone. 197 * <p> 198 * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date. 199 * Specifying the time-zone avoids dependence on the default time-zone. 200 * <p> 201 * Using this method will prevent the ability to use an alternate clock for testing 202 * because the clock is hard-coded. 203 * 204 * @param zone the zone ID to use, not null 205 * @return the current date using the system clock, not null 206 */ 207 public static LocalDate now(ZoneId zone) { 208 return now(Clock.system(zone)); 209 } 210 211 /** 212 * Obtains the current date from the specified clock. 213 * <p> 214 * This will query the specified clock to obtain the current date - today. 215 * Using this method allows the use of an alternate clock for testing. 216 * The alternate clock may be introduced using {@link Clock dependency injection}. 217 * 218 * @param clock the clock to use, not null 219 * @return the current date, not null 220 */ 221 public static LocalDate now(Clock clock) { 222 Objects.requireNonNull(clock, "clock"); 223 final Instant now = clock.instant(); // called once 224 return ofInstant(now, clock.getZone()); 225 } 226 227 //----------------------------------------------------------------------- 228 /** 229 * Obtains an instance of {@code LocalDate} from a year, month and day. 230 * <p> 231 * This returns a {@code LocalDate} with the specified year, month and day-of-month. 232 * The day must be valid for the year and month, otherwise an exception will be thrown. 233 * 234 * @param year the year to represent, from MIN_YEAR to MAX_YEAR 235 * @param month the month-of-year to represent, not null 236 * @param dayOfMonth the day-of-month to represent, from 1 to 31 237 * @return the local date, not null 238 * @throws DateTimeException if the value of any field is out of range, 239 * or if the day-of-month is invalid for the month-year 240 */ 241 public static LocalDate of(int year, Month month, int dayOfMonth) { 242 YEAR.checkValidValue(year); 243 Objects.requireNonNull(month, "month"); 244 DAY_OF_MONTH.checkValidValue(dayOfMonth); 245 return create(year, month.getValue(), dayOfMonth); 246 } 247 248 /** 249 * Obtains an instance of {@code LocalDate} from a year, month and day. 250 * <p> 251 * This returns a {@code LocalDate} with the specified year, month and day-of-month. 252 * The day must be valid for the year and month, otherwise an exception will be thrown. 253 * 254 * @param year the year to represent, from MIN_YEAR to MAX_YEAR 255 * @param month the month-of-year to represent, from 1 (January) to 12 (December) 256 * @param dayOfMonth the day-of-month to represent, from 1 to 31 257 * @return the local date, not null 258 * @throws DateTimeException if the value of any field is out of range, 259 * or if the day-of-month is invalid for the month-year 260 */ 261 public static LocalDate of(int year, int month, int dayOfMonth) { 262 YEAR.checkValidValue(year); 263 MONTH_OF_YEAR.checkValidValue(month); 264 DAY_OF_MONTH.checkValidValue(dayOfMonth); 265 return create(year, month, dayOfMonth); 266 } 267 268 //----------------------------------------------------------------------- 269 /** 270 * Obtains an instance of {@code LocalDate} from a year and day-of-year. 271 * <p> 272 * This returns a {@code LocalDate} with the specified year and day-of-year. 273 * The day-of-year must be valid for the year, otherwise an exception will be thrown. 274 * 275 * @param year the year to represent, from MIN_YEAR to MAX_YEAR 276 * @param dayOfYear the day-of-year to represent, from 1 to 366 277 * @return the local date, not null 278 * @throws DateTimeException if the value of any field is out of range, 279 * or if the day-of-year is invalid for the year 280 */ 281 public static LocalDate ofYearDay(int year, int dayOfYear) { 282 YEAR.checkValidValue(year); 283 DAY_OF_YEAR.checkValidValue(dayOfYear); 284 boolean leap = IsoChronology.INSTANCE.isLeapYear(year); 285 if (dayOfYear == 366 && leap == false) { 286 throw new DateTimeException("Invalid date 'DayOfYear 366' as '" + year + "' is not a leap year"); 287 } 288 Month moy = Month.of((dayOfYear - 1) / 31 + 1); 289 int monthEnd = moy.firstDayOfYear(leap) + moy.length(leap) - 1; 290 if (dayOfYear > monthEnd) { 291 moy = moy.plus(1); 292 } 293 int dom = dayOfYear - moy.firstDayOfYear(leap) + 1; 294 return new LocalDate(year, moy.getValue(), dom); 295 } 296 297 //----------------------------------------------------------------------- 298 /** 299 * Obtains an instance of {@code LocalDate} from an {@code Instant} and zone ID. 300 * <p> 301 * This creates a local date based on the specified instant. 302 * First, the offset from UTC/Greenwich is obtained using the zone ID and instant, 303 * which is simple as there is only one valid offset for each instant. 304 * Then, the instant and offset are used to calculate the local date. 305 * 306 * @param instant the instant to create the date from, not null 307 * @param zone the time-zone, which may be an offset, not null 308 * @return the local date, not null 309 * @throws DateTimeException if the result exceeds the supported range 310 */ 311 public static LocalDate ofInstant(Instant instant, ZoneId zone) { 312 Objects.requireNonNull(instant, "instant"); 313 Objects.requireNonNull(zone, "zone"); 314 ZoneRules rules = zone.getRules(); 315 ZoneOffset offset = rules.getOffset(instant); 316 long localSecond = instant.getEpochSecond() + offset.getTotalSeconds(); 317 long localEpochDay = Math.floorDiv(localSecond, SECONDS_PER_DAY); 318 return ofEpochDay(localEpochDay); 319 } 320 321 //----------------------------------------------------------------------- 322 /** 323 * Obtains an instance of {@code LocalDate} from the epoch day count. 324 * <p> 325 * This returns a {@code LocalDate} with the specified epoch-day. 326 * The {@link ChronoField#EPOCH_DAY EPOCH_DAY} is a simple incrementing count 327 * of days where day 0 is 1970-01-01. Negative numbers represent earlier days. 328 * 329 * @param epochDay the Epoch Day to convert, based on the epoch 1970-01-01 330 * @return the local date, not null 331 * @throws DateTimeException if the epoch day exceeds the supported date range 332 */ 333 public static LocalDate ofEpochDay(long epochDay) { 334 long zeroDay = epochDay + DAYS_0000_TO_1970; 335 // find the march-based year 336 zeroDay -= 60; // adjust to 0000-03-01 so leap day is at end of four year cycle 337 long adjust = 0; 338 if (zeroDay < 0) { 339 // adjust negative years to positive for calculation 340 long adjustCycles = (zeroDay + 1) / DAYS_PER_CYCLE - 1; 341 adjust = adjustCycles * 400; 342 zeroDay += -adjustCycles * DAYS_PER_CYCLE; 343 } 344 long yearEst = (400 * zeroDay + 591) / DAYS_PER_CYCLE; 345 long doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400); 346 if (doyEst < 0) { 347 // fix estimate 348 yearEst--; 349 doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400); 350 } 351 yearEst += adjust; // reset any negative year 352 int marchDoy0 = (int) doyEst; 353 354 // convert march-based values back to january-based 355 int marchMonth0 = (marchDoy0 * 5 + 2) / 153; 356 int month = (marchMonth0 + 2) % 12 + 1; 357 int dom = marchDoy0 - (marchMonth0 * 306 + 5) / 10 + 1; 358 yearEst += marchMonth0 / 10; 359 360 // check year now we are certain it is correct 361 int year = YEAR.checkValidIntValue(yearEst); 362 return new LocalDate(year, month, dom); 363 } 364 365 //----------------------------------------------------------------------- 366 /** 367 * Obtains an instance of {@code LocalDate} from a temporal object. 368 * <p> 369 * This obtains a local date based on the specified temporal. 370 * A {@code TemporalAccessor} represents an arbitrary set of date and time information, 371 * which this factory converts to an instance of {@code LocalDate}. 372 * <p> 373 * The conversion uses the {@link TemporalQueries#localDate()} query, which relies 374 * on extracting the {@link ChronoField#EPOCH_DAY EPOCH_DAY} field. 375 * <p> 376 * This method matches the signature of the functional interface {@link TemporalQuery} 377 * allowing it to be used as a query via method reference, {@code LocalDate::from}. 378 * 379 * @param temporal the temporal object to convert, not null 380 * @return the local date, not null 381 * @throws DateTimeException if unable to convert to a {@code LocalDate} 382 */ 383 public static LocalDate from(TemporalAccessor temporal) { 384 Objects.requireNonNull(temporal, "temporal"); 385 LocalDate date = temporal.query(TemporalQueries.localDate()); 386 if (date == null) { 387 throw new DateTimeException("Unable to obtain LocalDate from TemporalAccessor: " + 388 temporal + " of type " + temporal.getClass().getName()); 389 } 390 return date; 391 } 392 393 //----------------------------------------------------------------------- 394 /** 395 * Obtains an instance of {@code LocalDate} from a text string such as {@code 2007-12-03}. 396 * <p> 397 * The string must represent a valid date and is parsed using 398 * {@link java.time.format.DateTimeFormatter#ISO_LOCAL_DATE}. 399 * 400 * @param text the text to parse such as "2007-12-03", not null 401 * @return the parsed local date, not null 402 * @throws DateTimeParseException if the text cannot be parsed 403 */ 404 public static LocalDate parse(CharSequence text) { 405 return parse(text, DateTimeFormatter.ISO_LOCAL_DATE); 406 } 407 408 /** 409 * Obtains an instance of {@code LocalDate} from a text string using a specific formatter. 410 * <p> 411 * The text is parsed using the formatter, returning a date. 412 * 413 * @param text the text to parse, not null 414 * @param formatter the formatter to use, not null 415 * @return the parsed local date, not null 416 * @throws DateTimeParseException if the text cannot be parsed 417 */ 418 public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) { 419 Objects.requireNonNull(formatter, "formatter"); 420 return formatter.parse(text, LocalDate::from); 421 } 422 423 //----------------------------------------------------------------------- 424 /** 425 * Creates a local date from the year, month and day fields. 426 * 427 * @param year the year to represent, validated from MIN_YEAR to MAX_YEAR 428 * @param month the month-of-year to represent, from 1 to 12, validated 429 * @param dayOfMonth the day-of-month to represent, validated from 1 to 31 430 * @return the local date, not null 431 * @throws DateTimeException if the day-of-month is invalid for the month-year 432 */ 433 private static LocalDate create(int year, int month, int dayOfMonth) { 434 if (dayOfMonth > 28) { 435 int dom = 31; 436 switch (month) { 437 case 2: 438 dom = (IsoChronology.INSTANCE.isLeapYear(year) ? 29 : 28); 439 break; 440 case 4: 441 case 6: 442 case 9: 443 case 11: 444 dom = 30; 445 break; 446 } 447 if (dayOfMonth > dom) { 448 if (dayOfMonth == 29) { 449 throw new DateTimeException("Invalid date 'February 29' as '" + year + "' is not a leap year"); 450 } else { 451 throw new DateTimeException("Invalid date '" + Month.of(month).name() + " " + dayOfMonth + "'"); 452 } 453 } 454 } 455 return new LocalDate(year, month, dayOfMonth); 456 } 457 458 /** 459 * Resolves the date, resolving days past the end of month. 460 * 461 * @param year the year to represent, validated from MIN_YEAR to MAX_YEAR 462 * @param month the month-of-year to represent, validated from 1 to 12 463 * @param day the day-of-month to represent, validated from 1 to 31 464 * @return the resolved date, not null 465 */ 466 private static LocalDate resolvePreviousValid(int year, int month, int day) { 467 switch (month) { 468 case 2: 469 day = Math.min(day, IsoChronology.INSTANCE.isLeapYear(year) ? 29 : 28); 470 break; 471 case 4: 472 case 6: 473 case 9: 474 case 11: 475 day = Math.min(day, 30); 476 break; 477 } 478 return new LocalDate(year, month, day); 479 } 480 481 /** 482 * Constructor, previously validated. 483 * 484 * @param year the year to represent, from MIN_YEAR to MAX_YEAR 485 * @param month the month-of-year to represent, not null 486 * @param dayOfMonth the day-of-month to represent, valid for year-month, from 1 to 31 487 */ 488 private LocalDate(int year, int month, int dayOfMonth) { 489 this.year = year; 490 this.month = (short) month; 491 this.day = (short) dayOfMonth; 492 } 493 494 //----------------------------------------------------------------------- 495 /** 496 * Checks if the specified field is supported. 497 * <p> 498 * This checks if this date can be queried for the specified field. 499 * If false, then calling the {@link #range(TemporalField) range}, 500 * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)} 501 * methods will throw an exception. 502 * <p> 503 * If the field is a {@link ChronoField} then the query is implemented here. 504 * The supported fields are: 505 * <ul> 506 * <li>{@code DAY_OF_WEEK} 507 * <li>{@code ALIGNED_DAY_OF_WEEK_IN_MONTH} 508 * <li>{@code ALIGNED_DAY_OF_WEEK_IN_YEAR} 509 * <li>{@code DAY_OF_MONTH} 510 * <li>{@code DAY_OF_YEAR} 511 * <li>{@code EPOCH_DAY} 512 * <li>{@code ALIGNED_WEEK_OF_MONTH} 513 * <li>{@code ALIGNED_WEEK_OF_YEAR} 514 * <li>{@code MONTH_OF_YEAR} 515 * <li>{@code PROLEPTIC_MONTH} 516 * <li>{@code YEAR_OF_ERA} 517 * <li>{@code YEAR} 518 * <li>{@code ERA} 519 * </ul> 520 * All other {@code ChronoField} instances will return false. 521 * <p> 522 * If the field is not a {@code ChronoField}, then the result of this method 523 * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)} 524 * passing {@code this} as the argument. 525 * Whether the field is supported is determined by the field. 526 * 527 * @param field the field to check, null returns false 528 * @return true if the field is supported on this date, false if not 529 */ 530 @Override // override for Javadoc 531 public boolean isSupported(TemporalField field) { 532 return ChronoLocalDate.super.isSupported(field); 533 } 534 535 /** 536 * Checks if the specified unit is supported. 537 * <p> 538 * This checks if the specified unit can be added to, or subtracted from, this date. 539 * If false, then calling the {@link #plus(long, TemporalUnit)} and 540 * {@link #minus(long, TemporalUnit) minus} methods will throw an exception. 541 * <p> 542 * If the unit is a {@link ChronoUnit} then the query is implemented here. 543 * The supported units are: 544 * <ul> 545 * <li>{@code DAYS} 546 * <li>{@code WEEKS} 547 * <li>{@code MONTHS} 548 * <li>{@code YEARS} 549 * <li>{@code DECADES} 550 * <li>{@code CENTURIES} 551 * <li>{@code MILLENNIA} 552 * <li>{@code ERAS} 553 * </ul> 554 * All other {@code ChronoUnit} instances will return false. 555 * <p> 556 * If the unit is not a {@code ChronoUnit}, then the result of this method 557 * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)} 558 * passing {@code this} as the argument. 559 * Whether the unit is supported is determined by the unit. 560 * 561 * @param unit the unit to check, null returns false 562 * @return true if the unit can be added/subtracted, false if not 563 */ 564 @Override // override for Javadoc 565 public boolean isSupported(TemporalUnit unit) { 566 return ChronoLocalDate.super.isSupported(unit); 567 } 568 569 //----------------------------------------------------------------------- 570 /** 571 * Gets the range of valid values for the specified field. 572 * <p> 573 * The range object expresses the minimum and maximum valid values for a field. 574 * This date is used to enhance the accuracy of the returned range. 575 * If it is not possible to return the range, because the field is not supported 576 * or for some other reason, an exception is thrown. 577 * <p> 578 * If the field is a {@link ChronoField} then the query is implemented here. 579 * The {@link #isSupported(TemporalField) supported fields} will return 580 * appropriate range instances. 581 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 582 * <p> 583 * If the field is not a {@code ChronoField}, then the result of this method 584 * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)} 585 * passing {@code this} as the argument. 586 * Whether the range can be obtained is determined by the field. 587 * 588 * @param field the field to query the range for, not null 589 * @return the range of valid values for the field, not null 590 * @throws DateTimeException if the range for the field cannot be obtained 591 * @throws UnsupportedTemporalTypeException if the field is not supported 592 */ 593 @Override 594 public ValueRange range(TemporalField field) { 595 if (field instanceof ChronoField) { 596 ChronoField f = (ChronoField) field; 597 if (f.isDateBased()) { 598 switch (f) { 599 case DAY_OF_MONTH: return ValueRange.of(1, lengthOfMonth()); 600 case DAY_OF_YEAR: return ValueRange.of(1, lengthOfYear()); 601 case ALIGNED_WEEK_OF_MONTH: return ValueRange.of(1, getMonth() == Month.FEBRUARY && isLeapYear() == false ? 4 : 5); 602 case YEAR_OF_ERA: 603 return (getYear() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE)); 604 } 605 return field.range(); 606 } 607 throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 608 } 609 return field.rangeRefinedBy(this); 610 } 611 612 /** 613 * Gets the value of the specified field from this date as an {@code int}. 614 * <p> 615 * This queries this date for the value of the specified field. 616 * The returned value will always be within the valid range of values for the field. 617 * If it is not possible to return the value, because the field is not supported 618 * or for some other reason, an exception is thrown. 619 * <p> 620 * If the field is a {@link ChronoField} then the query is implemented here. 621 * The {@link #isSupported(TemporalField) supported fields} will return valid 622 * values based on this date, except {@code EPOCH_DAY} and {@code PROLEPTIC_MONTH} 623 * which are too large to fit in an {@code int} and throw an {@code UnsupportedTemporalTypeException}. 624 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 625 * <p> 626 * If the field is not a {@code ChronoField}, then the result of this method 627 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 628 * passing {@code this} as the argument. Whether the value can be obtained, 629 * and what the value represents, is determined by the field. 630 * 631 * @param field the field to get, not null 632 * @return the value for the field 633 * @throws DateTimeException if a value for the field cannot be obtained or 634 * the value is outside the range of valid values for the field 635 * @throws UnsupportedTemporalTypeException if the field is not supported or 636 * the range of values exceeds an {@code int} 637 * @throws ArithmeticException if numeric overflow occurs 638 */ 639 @Override // override for Javadoc and performance 640 public int get(TemporalField field) { 641 if (field instanceof ChronoField) { 642 return get0(field); 643 } 644 return ChronoLocalDate.super.get(field); 645 } 646 647 /** 648 * Gets the value of the specified field from this date as a {@code long}. 649 * <p> 650 * This queries this date for the value of the specified field. 651 * If it is not possible to return the value, because the field is not supported 652 * or for some other reason, an exception is thrown. 653 * <p> 654 * If the field is a {@link ChronoField} then the query is implemented here. 655 * The {@link #isSupported(TemporalField) supported fields} will return valid 656 * values based on this date. 657 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 658 * <p> 659 * If the field is not a {@code ChronoField}, then the result of this method 660 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 661 * passing {@code this} as the argument. Whether the value can be obtained, 662 * and what the value represents, is determined by the field. 663 * 664 * @param field the field to get, not null 665 * @return the value for the field 666 * @throws DateTimeException if a value for the field cannot be obtained 667 * @throws UnsupportedTemporalTypeException if the field is not supported 668 * @throws ArithmeticException if numeric overflow occurs 669 */ 670 @Override 671 public long getLong(TemporalField field) { 672 if (field instanceof ChronoField) { 673 if (field == EPOCH_DAY) { 674 return toEpochDay(); 675 } 676 if (field == PROLEPTIC_MONTH) { 677 return getProlepticMonth(); 678 } 679 return get0(field); 680 } 681 return field.getFrom(this); 682 } 683 684 private int get0(TemporalField field) { 685 switch ((ChronoField) field) { 686 case DAY_OF_WEEK: return getDayOfWeek().getValue(); 687 case ALIGNED_DAY_OF_WEEK_IN_MONTH: return ((day - 1) % 7) + 1; 688 case ALIGNED_DAY_OF_WEEK_IN_YEAR: return ((getDayOfYear() - 1) % 7) + 1; 689 case DAY_OF_MONTH: return day; 690 case DAY_OF_YEAR: return getDayOfYear(); 691 case EPOCH_DAY: throw new UnsupportedTemporalTypeException("Invalid field 'EpochDay' for get() method, use getLong() instead"); 692 case ALIGNED_WEEK_OF_MONTH: return ((day - 1) / 7) + 1; 693 case ALIGNED_WEEK_OF_YEAR: return ((getDayOfYear() - 1) / 7) + 1; 694 case MONTH_OF_YEAR: return month; 695 case PROLEPTIC_MONTH: throw new UnsupportedTemporalTypeException("Invalid field 'ProlepticMonth' for get() method, use getLong() instead"); 696 case YEAR_OF_ERA: return (year >= 1 ? year : 1 - year); 697 case YEAR: return year; 698 case ERA: return (year >= 1 ? 1 : 0); 699 } 700 throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 701 } 702 703 private long getProlepticMonth() { 704 return (year * 12L + month - 1); 705 } 706 707 //----------------------------------------------------------------------- 708 /** 709 * Gets the chronology of this date, which is the ISO calendar system. 710 * <p> 711 * The {@code Chronology} represents the calendar system in use. 712 * The ISO-8601 calendar system is the modern civil calendar system used today 713 * in most of the world. It is equivalent to the proleptic Gregorian calendar 714 * system, in which today's rules for leap years are applied for all time. 715 * 716 * @return the ISO chronology, not null 717 */ 718 @Override 719 public IsoChronology getChronology() { 720 return IsoChronology.INSTANCE; 721 } 722 723 /** 724 * Gets the era applicable at this date. 725 * <p> 726 * The official ISO-8601 standard does not define eras, however {@code IsoChronology} does. 727 * It defines two eras, 'CE' from year one onwards and 'BCE' from year zero backwards. 728 * Since dates before the Julian-Gregorian cutover are not in line with history, 729 * the cutover between 'BCE' and 'CE' is also not aligned with the commonly used 730 * eras, often referred to using 'BC' and 'AD'. 731 * <p> 732 * Users of this class should typically ignore this method as it exists primarily 733 * to fulfill the {@link ChronoLocalDate} contract where it is necessary to support 734 * the Japanese calendar system. 735 * 736 * @return the IsoEra applicable at this date, not null 737 */ 738 @Override // override for Javadoc 739 public IsoEra getEra() { 740 return (getYear() >= 1 ? IsoEra.CE : IsoEra.BCE); 741 } 742 743 /** 744 * Gets the year field. 745 * <p> 746 * This method returns the primitive {@code int} value for the year. 747 * <p> 748 * The year returned by this method is proleptic as per {@code get(YEAR)}. 749 * To obtain the year-of-era, use {@code get(YEAR_OF_ERA)}. 750 * 751 * @return the year, from MIN_YEAR to MAX_YEAR 752 */ 753 public int getYear() { 754 return year; 755 } 756 757 /** 758 * Gets the month-of-year field from 1 to 12. 759 * <p> 760 * This method returns the month as an {@code int} from 1 to 12. 761 * Application code is frequently clearer if the enum {@link Month} 762 * is used by calling {@link #getMonth()}. 763 * 764 * @return the month-of-year, from 1 to 12 765 * @see #getMonth() 766 */ 767 public int getMonthValue() { 768 return month; 769 } 770 771 /** 772 * Gets the month-of-year field using the {@code Month} enum. 773 * <p> 774 * This method returns the enum {@link Month} for the month. 775 * This avoids confusion as to what {@code int} values mean. 776 * If you need access to the primitive {@code int} value then the enum 777 * provides the {@link Month#getValue() int value}. 778 * 779 * @return the month-of-year, not null 780 * @see #getMonthValue() 781 */ 782 public Month getMonth() { 783 return Month.of(month); 784 } 785 786 /** 787 * Gets the day-of-month field. 788 * <p> 789 * This method returns the primitive {@code int} value for the day-of-month. 790 * 791 * @return the day-of-month, from 1 to 31 792 */ 793 public int getDayOfMonth() { 794 return day; 795 } 796 797 /** 798 * Gets the day-of-year field. 799 * <p> 800 * This method returns the primitive {@code int} value for the day-of-year. 801 * 802 * @return the day-of-year, from 1 to 365, or 366 in a leap year 803 */ 804 public int getDayOfYear() { 805 return getMonth().firstDayOfYear(isLeapYear()) + day - 1; 806 } 807 808 /** 809 * Gets the day-of-week field, which is an enum {@code DayOfWeek}. 810 * <p> 811 * This method returns the enum {@link DayOfWeek} for the day-of-week. 812 * This avoids confusion as to what {@code int} values mean. 813 * If you need access to the primitive {@code int} value then the enum 814 * provides the {@link DayOfWeek#getValue() int value}. 815 * <p> 816 * Additional information can be obtained from the {@code DayOfWeek}. 817 * This includes textual names of the values. 818 * 819 * @return the day-of-week, not null 820 */ 821 public DayOfWeek getDayOfWeek() { 822 int dow0 = (int)Math.floorMod(toEpochDay() + 3, 7); 823 return DayOfWeek.of(dow0 + 1); 824 } 825 826 //----------------------------------------------------------------------- 827 /** 828 * Checks if the year is a leap year, according to the ISO proleptic 829 * calendar system rules. 830 * <p> 831 * This method applies the current rules for leap years across the whole time-line. 832 * In general, a year is a leap year if it is divisible by four without 833 * remainder. However, years divisible by 100, are not leap years, with 834 * the exception of years divisible by 400 which are. 835 * <p> 836 * For example, 1904 is a leap year it is divisible by 4. 837 * 1900 was not a leap year as it is divisible by 100, however 2000 was a 838 * leap year as it is divisible by 400. 839 * <p> 840 * The calculation is proleptic - applying the same rules into the far future and far past. 841 * This is historically inaccurate, but is correct for the ISO-8601 standard. 842 * 843 * @return true if the year is leap, false otherwise 844 */ 845 @Override // override for Javadoc and performance 846 public boolean isLeapYear() { 847 return IsoChronology.INSTANCE.isLeapYear(year); 848 } 849 850 /** 851 * Returns the length of the month represented by this date. 852 * <p> 853 * This returns the length of the month in days. 854 * For example, a date in January would return 31. 855 * 856 * @return the length of the month in days 857 */ 858 @Override 859 public int lengthOfMonth() { 860 switch (month) { 861 case 2: 862 return (isLeapYear() ? 29 : 28); 863 case 4: 864 case 6: 865 case 9: 866 case 11: 867 return 30; 868 default: 869 return 31; 870 } 871 } 872 873 /** 874 * Returns the length of the year represented by this date. 875 * <p> 876 * This returns the length of the year in days, either 365 or 366. 877 * 878 * @return 366 if the year is leap, 365 otherwise 879 */ 880 @Override // override for Javadoc and performance 881 public int lengthOfYear() { 882 return (isLeapYear() ? 366 : 365); 883 } 884 885 //----------------------------------------------------------------------- 886 /** 887 * Returns an adjusted copy of this date. 888 * <p> 889 * This returns a {@code LocalDate}, based on this one, with the date adjusted. 890 * The adjustment takes place using the specified adjuster strategy object. 891 * Read the documentation of the adjuster to understand what adjustment will be made. 892 * <p> 893 * A simple adjuster might simply set the one of the fields, such as the year field. 894 * A more complex adjuster might set the date to the last day of the month. 895 * <p> 896 * A selection of common adjustments is provided in 897 * {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}. 898 * These include finding the "last day of the month" and "next Wednesday". 899 * Key date-time classes also implement the {@code TemporalAdjuster} interface, 900 * such as {@link Month} and {@link java.time.MonthDay MonthDay}. 901 * The adjuster is responsible for handling special cases, such as the varying 902 * lengths of month and leap years. 903 * <p> 904 * For example this code returns a date on the last day of July: 905 * <pre> 906 * import static java.time.Month.*; 907 * import static java.time.temporal.TemporalAdjusters.*; 908 * 909 * result = localDate.with(JULY).with(lastDayOfMonth()); 910 * </pre> 911 * <p> 912 * The result of this method is obtained by invoking the 913 * {@link TemporalAdjuster#adjustInto(Temporal)} method on the 914 * specified adjuster passing {@code this} as the argument. 915 * <p> 916 * This instance is immutable and unaffected by this method call. 917 * 918 * @param adjuster the adjuster to use, not null 919 * @return a {@code LocalDate} based on {@code this} with the adjustment made, not null 920 * @throws DateTimeException if the adjustment cannot be made 921 * @throws ArithmeticException if numeric overflow occurs 922 */ 923 @Override 924 public LocalDate with(TemporalAdjuster adjuster) { 925 // optimizations 926 if (adjuster instanceof LocalDate) { 927 return (LocalDate) adjuster; 928 } 929 return (LocalDate) adjuster.adjustInto(this); 930 } 931 932 /** 933 * Returns a copy of this date with the specified field set to a new value. 934 * <p> 935 * This returns a {@code LocalDate}, based on this one, with the value 936 * for the specified field changed. 937 * This can be used to change any supported field, such as the year, month or day-of-month. 938 * If it is not possible to set the value, because the field is not supported or for 939 * some other reason, an exception is thrown. 940 * <p> 941 * In some cases, changing the specified field can cause the resulting date to become invalid, 942 * such as changing the month from 31st January to February would make the day-of-month invalid. 943 * In cases like this, the field is responsible for resolving the date. Typically it will choose 944 * the previous valid date, which would be the last valid day of February in this example. 945 * <p> 946 * If the field is a {@link ChronoField} then the adjustment is implemented here. 947 * The supported fields behave as follows: 948 * <ul> 949 * <li>{@code DAY_OF_WEEK} - 950 * Returns a {@code LocalDate} with the specified day-of-week. 951 * The date is adjusted up to 6 days forward or backward within the boundary 952 * of a Monday to Sunday week. 953 * <li>{@code ALIGNED_DAY_OF_WEEK_IN_MONTH} - 954 * Returns a {@code LocalDate} with the specified aligned-day-of-week. 955 * The date is adjusted to the specified month-based aligned-day-of-week. 956 * Aligned weeks are counted such that the first week of a given month starts 957 * on the first day of that month. 958 * This may cause the date to be moved up to 6 days into the following month. 959 * <li>{@code ALIGNED_DAY_OF_WEEK_IN_YEAR} - 960 * Returns a {@code LocalDate} with the specified aligned-day-of-week. 961 * The date is adjusted to the specified year-based aligned-day-of-week. 962 * Aligned weeks are counted such that the first week of a given year starts 963 * on the first day of that year. 964 * This may cause the date to be moved up to 6 days into the following year. 965 * <li>{@code DAY_OF_MONTH} - 966 * Returns a {@code LocalDate} with the specified day-of-month. 967 * The month and year will be unchanged. If the day-of-month is invalid for the 968 * year and month, then a {@code DateTimeException} is thrown. 969 * <li>{@code DAY_OF_YEAR} - 970 * Returns a {@code LocalDate} with the specified day-of-year. 971 * The year will be unchanged. If the day-of-year is invalid for the 972 * year, then a {@code DateTimeException} is thrown. 973 * <li>{@code EPOCH_DAY} - 974 * Returns a {@code LocalDate} with the specified epoch-day. 975 * This completely replaces the date and is equivalent to {@link #ofEpochDay(long)}. 976 * <li>{@code ALIGNED_WEEK_OF_MONTH} - 977 * Returns a {@code LocalDate} with the specified aligned-week-of-month. 978 * Aligned weeks are counted such that the first week of a given month starts 979 * on the first day of that month. 980 * This adjustment moves the date in whole week chunks to match the specified week. 981 * The result will have the same day-of-week as this date. 982 * This may cause the date to be moved into the following month. 983 * <li>{@code ALIGNED_WEEK_OF_YEAR} - 984 * Returns a {@code LocalDate} with the specified aligned-week-of-year. 985 * Aligned weeks are counted such that the first week of a given year starts 986 * on the first day of that year. 987 * This adjustment moves the date in whole week chunks to match the specified week. 988 * The result will have the same day-of-week as this date. 989 * This may cause the date to be moved into the following year. 990 * <li>{@code MONTH_OF_YEAR} - 991 * Returns a {@code LocalDate} with the specified month-of-year. 992 * The year will be unchanged. The day-of-month will also be unchanged, 993 * unless it would be invalid for the new month and year. In that case, the 994 * day-of-month is adjusted to the maximum valid value for the new month and year. 995 * <li>{@code PROLEPTIC_MONTH} - 996 * Returns a {@code LocalDate} with the specified proleptic-month. 997 * The day-of-month will be unchanged, unless it would be invalid for the new month 998 * and year. In that case, the day-of-month is adjusted to the maximum valid value 999 * for the new month and year. 1000 * <li>{@code YEAR_OF_ERA} - 1001 * Returns a {@code LocalDate} with the specified year-of-era. 1002 * The era and month will be unchanged. The day-of-month will also be unchanged, 1003 * unless it would be invalid for the new month and year. In that case, the 1004 * day-of-month is adjusted to the maximum valid value for the new month and year. 1005 * <li>{@code YEAR} - 1006 * Returns a {@code LocalDate} with the specified year. 1007 * The month will be unchanged. The day-of-month will also be unchanged, 1008 * unless it would be invalid for the new month and year. In that case, the 1009 * day-of-month is adjusted to the maximum valid value for the new month and year. 1010 * <li>{@code ERA} - 1011 * Returns a {@code LocalDate} with the specified era. 1012 * The year-of-era and month will be unchanged. The day-of-month will also be unchanged, 1013 * unless it would be invalid for the new month and year. In that case, the 1014 * day-of-month is adjusted to the maximum valid value for the new month and year. 1015 * </ul> 1016 * <p> 1017 * In all cases, if the new value is outside the valid range of values for the field 1018 * then a {@code DateTimeException} will be thrown. 1019 * <p> 1020 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 1021 * <p> 1022 * If the field is not a {@code ChronoField}, then the result of this method 1023 * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)} 1024 * passing {@code this} as the argument. In this case, the field determines 1025 * whether and how to adjust the instant. 1026 * <p> 1027 * This instance is immutable and unaffected by this method call. 1028 * 1029 * @param field the field to set in the result, not null 1030 * @param newValue the new value of the field in the result 1031 * @return a {@code LocalDate} based on {@code this} with the specified field set, not null 1032 * @throws DateTimeException if the field cannot be set 1033 * @throws UnsupportedTemporalTypeException if the field is not supported 1034 * @throws ArithmeticException if numeric overflow occurs 1035 */ 1036 @Override 1037 public LocalDate with(TemporalField field, long newValue) { 1038 if (field instanceof ChronoField) { 1039 ChronoField f = (ChronoField) field; 1040 f.checkValidValue(newValue); 1041 switch (f) { 1042 case DAY_OF_WEEK: return plusDays(newValue - getDayOfWeek().getValue()); 1043 case ALIGNED_DAY_OF_WEEK_IN_MONTH: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH)); 1044 case ALIGNED_DAY_OF_WEEK_IN_YEAR: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR)); 1045 case DAY_OF_MONTH: return withDayOfMonth((int) newValue); 1046 case DAY_OF_YEAR: return withDayOfYear((int) newValue); 1047 case EPOCH_DAY: return LocalDate.ofEpochDay(newValue); 1048 case ALIGNED_WEEK_OF_MONTH: return plusWeeks(newValue - getLong(ALIGNED_WEEK_OF_MONTH)); 1049 case ALIGNED_WEEK_OF_YEAR: return plusWeeks(newValue - getLong(ALIGNED_WEEK_OF_YEAR)); 1050 case MONTH_OF_YEAR: return withMonth((int) newValue); 1051 case PROLEPTIC_MONTH: return plusMonths(newValue - getProlepticMonth()); 1052 case YEAR_OF_ERA: return withYear((int) (year >= 1 ? newValue : 1 - newValue)); 1053 case YEAR: return withYear((int) newValue); 1054 case ERA: return (getLong(ERA) == newValue ? this : withYear(1 - year)); 1055 } 1056 throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 1057 } 1058 return field.adjustInto(this, newValue); 1059 } 1060 1061 //----------------------------------------------------------------------- 1062 /** 1063 * Returns a copy of this {@code LocalDate} with the year altered. 1064 * <p> 1065 * If the day-of-month is invalid for the year, it will be changed to the last valid day of the month. 1066 * <p> 1067 * This instance is immutable and unaffected by this method call. 1068 * 1069 * @param year the year to set in the result, from MIN_YEAR to MAX_YEAR 1070 * @return a {@code LocalDate} based on this date with the requested year, not null 1071 * @throws DateTimeException if the year value is invalid 1072 */ 1073 public LocalDate withYear(int year) { 1074 if (this.year == year) { 1075 return this; 1076 } 1077 YEAR.checkValidValue(year); 1078 return resolvePreviousValid(year, month, day); 1079 } 1080 1081 /** 1082 * Returns a copy of this {@code LocalDate} with the month-of-year altered. 1083 * <p> 1084 * If the day-of-month is invalid for the year, it will be changed to the last valid day of the month. 1085 * <p> 1086 * This instance is immutable and unaffected by this method call. 1087 * 1088 * @param month the month-of-year to set in the result, from 1 (January) to 12 (December) 1089 * @return a {@code LocalDate} based on this date with the requested month, not null 1090 * @throws DateTimeException if the month-of-year value is invalid 1091 */ 1092 public LocalDate withMonth(int month) { 1093 if (this.month == month) { 1094 return this; 1095 } 1096 MONTH_OF_YEAR.checkValidValue(month); 1097 return resolvePreviousValid(year, month, day); 1098 } 1099 1100 /** 1101 * Returns a copy of this {@code LocalDate} with the day-of-month altered. 1102 * <p> 1103 * If the resulting date is invalid, an exception is thrown. 1104 * <p> 1105 * This instance is immutable and unaffected by this method call. 1106 * 1107 * @param dayOfMonth the day-of-month to set in the result, from 1 to 28-31 1108 * @return a {@code LocalDate} based on this date with the requested day, not null 1109 * @throws DateTimeException if the day-of-month value is invalid, 1110 * or if the day-of-month is invalid for the month-year 1111 */ 1112 public LocalDate withDayOfMonth(int dayOfMonth) { 1113 if (this.day == dayOfMonth) { 1114 return this; 1115 } 1116 return of(year, month, dayOfMonth); 1117 } 1118 1119 /** 1120 * Returns a copy of this {@code LocalDate} with the day-of-year altered. 1121 * <p> 1122 * If the resulting date is invalid, an exception is thrown. 1123 * <p> 1124 * This instance is immutable and unaffected by this method call. 1125 * 1126 * @param dayOfYear the day-of-year to set in the result, from 1 to 365-366 1127 * @return a {@code LocalDate} based on this date with the requested day, not null 1128 * @throws DateTimeException if the day-of-year value is invalid, 1129 * or if the day-of-year is invalid for the year 1130 */ 1131 public LocalDate withDayOfYear(int dayOfYear) { 1132 if (this.getDayOfYear() == dayOfYear) { 1133 return this; 1134 } 1135 return ofYearDay(year, dayOfYear); 1136 } 1137 1138 //----------------------------------------------------------------------- 1139 /** 1140 * Returns a copy of this date with the specified amount added. 1141 * <p> 1142 * This returns a {@code LocalDate}, based on this one, with the specified amount added. 1143 * The amount is typically {@link Period} but may be any other type implementing 1144 * the {@link TemporalAmount} interface. 1145 * <p> 1146 * The calculation is delegated to the amount object by calling 1147 * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free 1148 * to implement the addition in any way it wishes, however it typically 1149 * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation 1150 * of the amount implementation to determine if it can be successfully added. 1151 * <p> 1152 * This instance is immutable and unaffected by this method call. 1153 * 1154 * @param amountToAdd the amount to add, not null 1155 * @return a {@code LocalDate} based on this date with the addition made, not null 1156 * @throws DateTimeException if the addition cannot be made 1157 * @throws ArithmeticException if numeric overflow occurs 1158 */ 1159 @Override 1160 public LocalDate plus(TemporalAmount amountToAdd) { 1161 if (amountToAdd instanceof Period) { 1162 Period periodToAdd = (Period) amountToAdd; 1163 return plusMonths(periodToAdd.toTotalMonths()).plusDays(periodToAdd.getDays()); 1164 } 1165 Objects.requireNonNull(amountToAdd, "amountToAdd"); 1166 return (LocalDate) amountToAdd.addTo(this); 1167 } 1168 1169 /** 1170 * Returns a copy of this date with the specified amount added. 1171 * <p> 1172 * This returns a {@code LocalDate}, based on this one, with the amount 1173 * in terms of the unit added. If it is not possible to add the amount, because the 1174 * unit is not supported or for some other reason, an exception is thrown. 1175 * <p> 1176 * In some cases, adding the amount can cause the resulting date to become invalid. 1177 * For example, adding one month to 31st January would result in 31st February. 1178 * In cases like this, the unit is responsible for resolving the date. 1179 * Typically it will choose the previous valid date, which would be the last valid 1180 * day of February in this example. 1181 * <p> 1182 * If the field is a {@link ChronoUnit} then the addition is implemented here. 1183 * The supported fields behave as follows: 1184 * <ul> 1185 * <li>{@code DAYS} - 1186 * Returns a {@code LocalDate} with the specified number of days added. 1187 * This is equivalent to {@link #plusDays(long)}. 1188 * <li>{@code WEEKS} - 1189 * Returns a {@code LocalDate} with the specified number of weeks added. 1190 * This is equivalent to {@link #plusWeeks(long)} and uses a 7 day week. 1191 * <li>{@code MONTHS} - 1192 * Returns a {@code LocalDate} with the specified number of months added. 1193 * This is equivalent to {@link #plusMonths(long)}. 1194 * The day-of-month will be unchanged unless it would be invalid for the new 1195 * month and year. In that case, the day-of-month is adjusted to the maximum 1196 * valid value for the new month and year. 1197 * <li>{@code YEARS} - 1198 * Returns a {@code LocalDate} with the specified number of years added. 1199 * This is equivalent to {@link #plusYears(long)}. 1200 * The day-of-month will be unchanged unless it would be invalid for the new 1201 * month and year. In that case, the day-of-month is adjusted to the maximum 1202 * valid value for the new month and year. 1203 * <li>{@code DECADES} - 1204 * Returns a {@code LocalDate} with the specified number of decades added. 1205 * This is equivalent to calling {@link #plusYears(long)} with the amount 1206 * multiplied by 10. 1207 * The day-of-month will be unchanged unless it would be invalid for the new 1208 * month and year. In that case, the day-of-month is adjusted to the maximum 1209 * valid value for the new month and year. 1210 * <li>{@code CENTURIES} - 1211 * Returns a {@code LocalDate} with the specified number of centuries added. 1212 * This is equivalent to calling {@link #plusYears(long)} with the amount 1213 * multiplied by 100. 1214 * The day-of-month will be unchanged unless it would be invalid for the new 1215 * month and year. In that case, the day-of-month is adjusted to the maximum 1216 * valid value for the new month and year. 1217 * <li>{@code MILLENNIA} - 1218 * Returns a {@code LocalDate} with the specified number of millennia added. 1219 * This is equivalent to calling {@link #plusYears(long)} with the amount 1220 * multiplied by 1,000. 1221 * The day-of-month will be unchanged unless it would be invalid for the new 1222 * month and year. In that case, the day-of-month is adjusted to the maximum 1223 * valid value for the new month and year. 1224 * <li>{@code ERAS} - 1225 * Returns a {@code LocalDate} with the specified number of eras added. 1226 * Only two eras are supported so the amount must be one, zero or minus one. 1227 * If the amount is non-zero then the year is changed such that the year-of-era 1228 * is unchanged. 1229 * The day-of-month will be unchanged unless it would be invalid for the new 1230 * month and year. In that case, the day-of-month is adjusted to the maximum 1231 * valid value for the new month and year. 1232 * </ul> 1233 * <p> 1234 * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}. 1235 * <p> 1236 * If the field is not a {@code ChronoUnit}, then the result of this method 1237 * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)} 1238 * passing {@code this} as the argument. In this case, the unit determines 1239 * whether and how to perform the addition. 1240 * <p> 1241 * This instance is immutable and unaffected by this method call. 1242 * 1243 * @param amountToAdd the amount of the unit to add to the result, may be negative 1244 * @param unit the unit of the amount to add, not null 1245 * @return a {@code LocalDate} based on this date with the specified amount added, not null 1246 * @throws DateTimeException if the addition cannot be made 1247 * @throws UnsupportedTemporalTypeException if the unit is not supported 1248 * @throws ArithmeticException if numeric overflow occurs 1249 */ 1250 @Override 1251 public LocalDate plus(long amountToAdd, TemporalUnit unit) { 1252 if (unit instanceof ChronoUnit) { 1253 ChronoUnit f = (ChronoUnit) unit; 1254 switch (f) { 1255 case DAYS: return plusDays(amountToAdd); 1256 case WEEKS: return plusWeeks(amountToAdd); 1257 case MONTHS: return plusMonths(amountToAdd); 1258 case YEARS: return plusYears(amountToAdd); 1259 case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10)); 1260 case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100)); 1261 case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000)); 1262 case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd)); 1263 } 1264 throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); 1265 } 1266 return unit.addTo(this, amountToAdd); 1267 } 1268 1269 //----------------------------------------------------------------------- 1270 /** 1271 * Returns a copy of this {@code LocalDate} with the specified number of years added. 1272 * <p> 1273 * This method adds the specified amount to the years field in three steps: 1274 * <ol> 1275 * <li>Add the input years to the year field</li> 1276 * <li>Check if the resulting date would be invalid</li> 1277 * <li>Adjust the day-of-month to the last valid day if necessary</li> 1278 * </ol> 1279 * <p> 1280 * For example, 2008-02-29 (leap year) plus one year would result in the 1281 * invalid date 2009-02-29 (standard year). Instead of returning an invalid 1282 * result, the last valid day of the month, 2009-02-28, is selected instead. 1283 * <p> 1284 * This instance is immutable and unaffected by this method call. 1285 * 1286 * @param yearsToAdd the years to add, may be negative 1287 * @return a {@code LocalDate} based on this date with the years added, not null 1288 * @throws DateTimeException if the result exceeds the supported date range 1289 */ 1290 public LocalDate plusYears(long yearsToAdd) { 1291 if (yearsToAdd == 0) { 1292 return this; 1293 } 1294 int newYear = YEAR.checkValidIntValue(year + yearsToAdd); // safe overflow 1295 return resolvePreviousValid(newYear, month, day); 1296 } 1297 1298 /** 1299 * Returns a copy of this {@code LocalDate} with the specified number of months added. 1300 * <p> 1301 * This method adds the specified amount to the months field in three steps: 1302 * <ol> 1303 * <li>Add the input months to the month-of-year field</li> 1304 * <li>Check if the resulting date would be invalid</li> 1305 * <li>Adjust the day-of-month to the last valid day if necessary</li> 1306 * </ol> 1307 * <p> 1308 * For example, 2007-03-31 plus one month would result in the invalid date 1309 * 2007-04-31. Instead of returning an invalid result, the last valid day 1310 * of the month, 2007-04-30, is selected instead. 1311 * <p> 1312 * This instance is immutable and unaffected by this method call. 1313 * 1314 * @param monthsToAdd the months to add, may be negative 1315 * @return a {@code LocalDate} based on this date with the months added, not null 1316 * @throws DateTimeException if the result exceeds the supported date range 1317 */ 1318 public LocalDate plusMonths(long monthsToAdd) { 1319 if (monthsToAdd == 0) { 1320 return this; 1321 } 1322 long monthCount = year * 12L + (month - 1); 1323 long calcMonths = monthCount + monthsToAdd; // safe overflow 1324 int newYear = YEAR.checkValidIntValue(Math.floorDiv(calcMonths, 12)); 1325 int newMonth = (int)Math.floorMod(calcMonths, 12) + 1; 1326 return resolvePreviousValid(newYear, newMonth, day); 1327 } 1328 1329 /** 1330 * Returns a copy of this {@code LocalDate} with the specified number of weeks added. 1331 * <p> 1332 * This method adds the specified amount in weeks to the days field incrementing 1333 * the month and year fields as necessary to ensure the result remains valid. 1334 * The result is only invalid if the maximum/minimum year is exceeded. 1335 * <p> 1336 * For example, 2008-12-31 plus one week would result in 2009-01-07. 1337 * <p> 1338 * This instance is immutable and unaffected by this method call. 1339 * 1340 * @param weeksToAdd the weeks to add, may be negative 1341 * @return a {@code LocalDate} based on this date with the weeks added, not null 1342 * @throws DateTimeException if the result exceeds the supported date range 1343 */ 1344 public LocalDate plusWeeks(long weeksToAdd) { 1345 return plusDays(Math.multiplyExact(weeksToAdd, 7)); 1346 } 1347 1348 /** 1349 * Returns a copy of this {@code LocalDate} with the specified number of days added. 1350 * <p> 1351 * This method adds the specified amount to the days field incrementing the 1352 * month and year fields as necessary to ensure the result remains valid. 1353 * The result is only invalid if the maximum/minimum year is exceeded. 1354 * <p> 1355 * For example, 2008-12-31 plus one day would result in 2009-01-01. 1356 * <p> 1357 * This instance is immutable and unaffected by this method call. 1358 * 1359 * @param daysToAdd the days to add, may be negative 1360 * @return a {@code LocalDate} based on this date with the days added, not null 1361 * @throws DateTimeException if the result exceeds the supported date range 1362 */ 1363 public LocalDate plusDays(long daysToAdd) { 1364 if (daysToAdd == 0) { 1365 return this; 1366 } 1367 long mjDay = Math.addExact(toEpochDay(), daysToAdd); 1368 return LocalDate.ofEpochDay(mjDay); 1369 } 1370 1371 //----------------------------------------------------------------------- 1372 /** 1373 * Returns a copy of this date with the specified amount subtracted. 1374 * <p> 1375 * This returns a {@code LocalDate}, based on this one, with the specified amount subtracted. 1376 * The amount is typically {@link Period} but may be any other type implementing 1377 * the {@link TemporalAmount} interface. 1378 * <p> 1379 * The calculation is delegated to the amount object by calling 1380 * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free 1381 * to implement the subtraction in any way it wishes, however it typically 1382 * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation 1383 * of the amount implementation to determine if it can be successfully subtracted. 1384 * <p> 1385 * This instance is immutable and unaffected by this method call. 1386 * 1387 * @param amountToSubtract the amount to subtract, not null 1388 * @return a {@code LocalDate} based on this date with the subtraction made, not null 1389 * @throws DateTimeException if the subtraction cannot be made 1390 * @throws ArithmeticException if numeric overflow occurs 1391 */ 1392 @Override 1393 public LocalDate minus(TemporalAmount amountToSubtract) { 1394 if (amountToSubtract instanceof Period) { 1395 Period periodToSubtract = (Period) amountToSubtract; 1396 return minusMonths(periodToSubtract.toTotalMonths()).minusDays(periodToSubtract.getDays()); 1397 } 1398 Objects.requireNonNull(amountToSubtract, "amountToSubtract"); 1399 return (LocalDate) amountToSubtract.subtractFrom(this); 1400 } 1401 1402 /** 1403 * Returns a copy of this date with the specified amount subtracted. 1404 * <p> 1405 * This returns a {@code LocalDate}, based on this one, with the amount 1406 * in terms of the unit subtracted. If it is not possible to subtract the amount, 1407 * because the unit is not supported or for some other reason, an exception is thrown. 1408 * <p> 1409 * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated. 1410 * See that method for a full description of how addition, and thus subtraction, works. 1411 * <p> 1412 * This instance is immutable and unaffected by this method call. 1413 * 1414 * @param amountToSubtract the amount of the unit to subtract from the result, may be negative 1415 * @param unit the unit of the amount to subtract, not null 1416 * @return a {@code LocalDate} based on this date with the specified amount subtracted, not null 1417 * @throws DateTimeException if the subtraction cannot be made 1418 * @throws UnsupportedTemporalTypeException if the unit is not supported 1419 * @throws ArithmeticException if numeric overflow occurs 1420 */ 1421 @Override 1422 public LocalDate minus(long amountToSubtract, TemporalUnit unit) { 1423 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); 1424 } 1425 1426 //----------------------------------------------------------------------- 1427 /** 1428 * Returns a copy of this {@code LocalDate} with the specified number of years subtracted. 1429 * <p> 1430 * This method subtracts the specified amount from the years field in three steps: 1431 * <ol> 1432 * <li>Subtract the input years from the year field</li> 1433 * <li>Check if the resulting date would be invalid</li> 1434 * <li>Adjust the day-of-month to the last valid day if necessary</li> 1435 * </ol> 1436 * <p> 1437 * For example, 2008-02-29 (leap year) minus one year would result in the 1438 * invalid date 2007-02-29 (standard year). Instead of returning an invalid 1439 * result, the last valid day of the month, 2007-02-28, is selected instead. 1440 * <p> 1441 * This instance is immutable and unaffected by this method call. 1442 * 1443 * @param yearsToSubtract the years to subtract, may be negative 1444 * @return a {@code LocalDate} based on this date with the years subtracted, not null 1445 * @throws DateTimeException if the result exceeds the supported date range 1446 */ 1447 public LocalDate minusYears(long yearsToSubtract) { 1448 return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract)); 1449 } 1450 1451 /** 1452 * Returns a copy of this {@code LocalDate} with the specified number of months subtracted. 1453 * <p> 1454 * This method subtracts the specified amount from the months field in three steps: 1455 * <ol> 1456 * <li>Subtract the input months from the month-of-year field</li> 1457 * <li>Check if the resulting date would be invalid</li> 1458 * <li>Adjust the day-of-month to the last valid day if necessary</li> 1459 * </ol> 1460 * <p> 1461 * For example, 2007-03-31 minus one month would result in the invalid date 1462 * 2007-02-31. Instead of returning an invalid result, the last valid day 1463 * of the month, 2007-02-28, is selected instead. 1464 * <p> 1465 * This instance is immutable and unaffected by this method call. 1466 * 1467 * @param monthsToSubtract the months to subtract, may be negative 1468 * @return a {@code LocalDate} based on this date with the months subtracted, not null 1469 * @throws DateTimeException if the result exceeds the supported date range 1470 */ 1471 public LocalDate minusMonths(long monthsToSubtract) { 1472 return (monthsToSubtract == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-monthsToSubtract)); 1473 } 1474 1475 /** 1476 * Returns a copy of this {@code LocalDate} with the specified number of weeks subtracted. 1477 * <p> 1478 * This method subtracts the specified amount in weeks from the days field decrementing 1479 * the month and year fields as necessary to ensure the result remains valid. 1480 * The result is only invalid if the maximum/minimum year is exceeded. 1481 * <p> 1482 * For example, 2009-01-07 minus one week would result in 2008-12-31. 1483 * <p> 1484 * This instance is immutable and unaffected by this method call. 1485 * 1486 * @param weeksToSubtract the weeks to subtract, may be negative 1487 * @return a {@code LocalDate} based on this date with the weeks subtracted, not null 1488 * @throws DateTimeException if the result exceeds the supported date range 1489 */ 1490 public LocalDate minusWeeks(long weeksToSubtract) { 1491 return (weeksToSubtract == Long.MIN_VALUE ? plusWeeks(Long.MAX_VALUE).plusWeeks(1) : plusWeeks(-weeksToSubtract)); 1492 } 1493 1494 /** 1495 * Returns a copy of this {@code LocalDate} with the specified number of days subtracted. 1496 * <p> 1497 * This method subtracts the specified amount from the days field decrementing the 1498 * month and year fields as necessary to ensure the result remains valid. 1499 * The result is only invalid if the maximum/minimum year is exceeded. 1500 * <p> 1501 * For example, 2009-01-01 minus one day would result in 2008-12-31. 1502 * <p> 1503 * This instance is immutable and unaffected by this method call. 1504 * 1505 * @param daysToSubtract the days to subtract, may be negative 1506 * @return a {@code LocalDate} based on this date with the days subtracted, not null 1507 * @throws DateTimeException if the result exceeds the supported date range 1508 */ 1509 public LocalDate minusDays(long daysToSubtract) { 1510 return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract)); 1511 } 1512 1513 //----------------------------------------------------------------------- 1514 /** 1515 * Queries this date using the specified query. 1516 * <p> 1517 * This queries this date using the specified query strategy object. 1518 * The {@code TemporalQuery} object defines the logic to be used to 1519 * obtain the result. Read the documentation of the query to understand 1520 * what the result of this method will be. 1521 * <p> 1522 * The result of this method is obtained by invoking the 1523 * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the 1524 * specified query passing {@code this} as the argument. 1525 * 1526 * @param <R> the type of the result 1527 * @param query the query to invoke, not null 1528 * @return the query result, null may be returned (defined by the query) 1529 * @throws DateTimeException if unable to query (defined by the query) 1530 * @throws ArithmeticException if numeric overflow occurs (defined by the query) 1531 */ 1532 @SuppressWarnings("unchecked") 1533 @Override 1534 public <R> R query(TemporalQuery<R> query) { 1535 if (query == TemporalQueries.localDate()) { 1536 return (R) this; 1537 } 1538 return ChronoLocalDate.super.query(query); 1539 } 1540 1541 /** 1542 * Adjusts the specified temporal object to have the same date as this object. 1543 * <p> 1544 * This returns a temporal object of the same observable type as the input 1545 * with the date changed to be the same as this. 1546 * <p> 1547 * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)} 1548 * passing {@link ChronoField#EPOCH_DAY} as the field. 1549 * <p> 1550 * In most cases, it is clearer to reverse the calling pattern by using 1551 * {@link Temporal#with(TemporalAdjuster)}: 1552 * <pre> 1553 * // these two lines are equivalent, but the second approach is recommended 1554 * temporal = thisLocalDate.adjustInto(temporal); 1555 * temporal = temporal.with(thisLocalDate); 1556 * </pre> 1557 * <p> 1558 * This instance is immutable and unaffected by this method call. 1559 * 1560 * @param temporal the target object to be adjusted, not null 1561 * @return the adjusted object, not null 1562 * @throws DateTimeException if unable to make the adjustment 1563 * @throws ArithmeticException if numeric overflow occurs 1564 */ 1565 @Override // override for Javadoc 1566 public Temporal adjustInto(Temporal temporal) { 1567 return ChronoLocalDate.super.adjustInto(temporal); 1568 } 1569 1570 /** 1571 * Calculates the amount of time until another date in terms of the specified unit. 1572 * <p> 1573 * This calculates the amount of time between two {@code LocalDate} 1574 * objects in terms of a single {@code TemporalUnit}. 1575 * The start and end points are {@code this} and the specified date. 1576 * The result will be negative if the end is before the start. 1577 * The {@code Temporal} passed to this method is converted to a 1578 * {@code LocalDate} using {@link #from(TemporalAccessor)}. 1579 * For example, the amount in days between two dates can be calculated 1580 * using {@code startDate.until(endDate, DAYS)}. 1581 * <p> 1582 * The calculation returns a whole number, representing the number of 1583 * complete units between the two dates. 1584 * For example, the amount in months between 2012-06-15 and 2012-08-14 1585 * will only be one month as it is one day short of two months. 1586 * <p> 1587 * There are two equivalent ways of using this method. 1588 * The first is to invoke this method. 1589 * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}: 1590 * <pre> 1591 * // these two lines are equivalent 1592 * amount = start.until(end, MONTHS); 1593 * amount = MONTHS.between(start, end); 1594 * </pre> 1595 * The choice should be made based on which makes the code more readable. 1596 * <p> 1597 * The calculation is implemented in this method for {@link ChronoUnit}. 1598 * The units {@code DAYS}, {@code WEEKS}, {@code MONTHS}, {@code YEARS}, 1599 * {@code DECADES}, {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} 1600 * are supported. Other {@code ChronoUnit} values will throw an exception. 1601 * <p> 1602 * If the unit is not a {@code ChronoUnit}, then the result of this method 1603 * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)} 1604 * passing {@code this} as the first argument and the converted input temporal 1605 * as the second argument. 1606 * <p> 1607 * This instance is immutable and unaffected by this method call. 1608 * 1609 * @param endExclusive the end date, exclusive, which is converted to a {@code LocalDate}, not null 1610 * @param unit the unit to measure the amount in, not null 1611 * @return the amount of time between this date and the end date 1612 * @throws DateTimeException if the amount cannot be calculated, or the end 1613 * temporal cannot be converted to a {@code LocalDate} 1614 * @throws UnsupportedTemporalTypeException if the unit is not supported 1615 * @throws ArithmeticException if numeric overflow occurs 1616 */ 1617 @Override 1618 public long until(Temporal endExclusive, TemporalUnit unit) { 1619 LocalDate end = LocalDate.from(endExclusive); 1620 if (unit instanceof ChronoUnit) { 1621 switch ((ChronoUnit) unit) { 1622 case DAYS: return daysUntil(end); 1623 case WEEKS: return daysUntil(end) / 7; 1624 case MONTHS: return monthsUntil(end); 1625 case YEARS: return monthsUntil(end) / 12; 1626 case DECADES: return monthsUntil(end) / 120; 1627 case CENTURIES: return monthsUntil(end) / 1200; 1628 case MILLENNIA: return monthsUntil(end) / 12000; 1629 case ERAS: return end.getLong(ERA) - getLong(ERA); 1630 } 1631 throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); 1632 } 1633 return unit.between(this, end); 1634 } 1635 1636 long daysUntil(LocalDate end) { 1637 return end.toEpochDay() - toEpochDay(); // no overflow 1638 } 1639 1640 private long monthsUntil(LocalDate end) { 1641 long packed1 = getProlepticMonth() * 32L + getDayOfMonth(); // no overflow 1642 long packed2 = end.getProlepticMonth() * 32L + end.getDayOfMonth(); // no overflow 1643 return (packed2 - packed1) / 32; 1644 } 1645 1646 /** 1647 * Calculates the period between this date and another date as a {@code Period}. 1648 * <p> 1649 * This calculates the period between two dates in terms of years, months and days. 1650 * The start and end points are {@code this} and the specified date. 1651 * The result will be negative if the end is before the start. 1652 * The negative sign will be the same in each of year, month and day. 1653 * <p> 1654 * The calculation is performed using the ISO calendar system. 1655 * If necessary, the input date will be converted to ISO. 1656 * <p> 1657 * The start date is included, but the end date is not. 1658 * The period is calculated by removing complete months, then calculating 1659 * the remaining number of days, adjusting to ensure that both have the same sign. 1660 * The number of months is then normalized into years and months based on a 12 month year. 1661 * A month is considered to be complete if the end day-of-month is greater 1662 * than or equal to the start day-of-month. 1663 * For example, from {@code 2010-01-15} to {@code 2011-03-18} is "1 year, 2 months and 3 days". 1664 * <p> 1665 * There are two equivalent ways of using this method. 1666 * The first is to invoke this method. 1667 * The second is to use {@link Period#between(LocalDate, LocalDate)}: 1668 * <pre> 1669 * // these two lines are equivalent 1670 * period = start.until(end); 1671 * period = Period.between(start, end); 1672 * </pre> 1673 * The choice should be made based on which makes the code more readable. 1674 * 1675 * @param endDateExclusive the end date, exclusive, which may be in any chronology, not null 1676 * @return the period between this date and the end date, not null 1677 */ 1678 @Override 1679 public Period until(ChronoLocalDate endDateExclusive) { 1680 LocalDate end = LocalDate.from(endDateExclusive); 1681 long totalMonths = end.getProlepticMonth() - this.getProlepticMonth(); // safe 1682 int days = end.day - this.day; 1683 if (totalMonths > 0 && days < 0) { 1684 totalMonths--; 1685 LocalDate calcDate = this.plusMonths(totalMonths); 1686 days = (int) (end.toEpochDay() - calcDate.toEpochDay()); // safe 1687 } else if (totalMonths < 0 && days > 0) { 1688 totalMonths++; 1689 days -= end.lengthOfMonth(); 1690 } 1691 long years = totalMonths / 12; // safe 1692 int months = (int) (totalMonths % 12); // safe 1693 return Period.of(Math.toIntExact(years), months, days); 1694 } 1695 1696 /** 1697 * Formats this date using the specified formatter. 1698 * <p> 1699 * This date will be passed to the formatter to produce a string. 1700 * 1701 * @param formatter the formatter to use, not null 1702 * @return the formatted date string, not null 1703 * @throws DateTimeException if an error occurs during printing 1704 */ 1705 @Override // override for Javadoc and performance 1706 public String format(DateTimeFormatter formatter) { 1707 Objects.requireNonNull(formatter, "formatter"); 1708 return formatter.format(this); 1709 } 1710 1711 //----------------------------------------------------------------------- 1712 /** 1713 * Combines this date with a time to create a {@code LocalDateTime}. 1714 * <p> 1715 * This returns a {@code LocalDateTime} formed from this date at the specified time. 1716 * All possible combinations of date and time are valid. 1717 * 1718 * @param time the time to combine with, not null 1719 * @return the local date-time formed from this date and the specified time, not null 1720 */ 1721 @Override 1722 public LocalDateTime atTime(LocalTime time) { 1723 return LocalDateTime.of(this, time); 1724 } 1725 1726 /** 1727 * Combines this date with a time to create a {@code LocalDateTime}. 1728 * <p> 1729 * This returns a {@code LocalDateTime} formed from this date at the 1730 * specified hour and minute. 1731 * The seconds and nanosecond fields will be set to zero. 1732 * The individual time fields must be within their valid range. 1733 * All possible combinations of date and time are valid. 1734 * 1735 * @param hour the hour-of-day to use, from 0 to 23 1736 * @param minute the minute-of-hour to use, from 0 to 59 1737 * @return the local date-time formed from this date and the specified time, not null 1738 * @throws DateTimeException if the value of any field is out of range 1739 */ 1740 public LocalDateTime atTime(int hour, int minute) { 1741 return atTime(LocalTime.of(hour, minute)); 1742 } 1743 1744 /** 1745 * Combines this date with a time to create a {@code LocalDateTime}. 1746 * <p> 1747 * This returns a {@code LocalDateTime} formed from this date at the 1748 * specified hour, minute and second. 1749 * The nanosecond field will be set to zero. 1750 * The individual time fields must be within their valid range. 1751 * All possible combinations of date and time are valid. 1752 * 1753 * @param hour the hour-of-day to use, from 0 to 23 1754 * @param minute the minute-of-hour to use, from 0 to 59 1755 * @param second the second-of-minute to represent, from 0 to 59 1756 * @return the local date-time formed from this date and the specified time, not null 1757 * @throws DateTimeException if the value of any field is out of range 1758 */ 1759 public LocalDateTime atTime(int hour, int minute, int second) { 1760 return atTime(LocalTime.of(hour, minute, second)); 1761 } 1762 1763 /** 1764 * Combines this date with a time to create a {@code LocalDateTime}. 1765 * <p> 1766 * This returns a {@code LocalDateTime} formed from this date at the 1767 * specified hour, minute, second and nanosecond. 1768 * The individual time fields must be within their valid range. 1769 * All possible combinations of date and time are valid. 1770 * 1771 * @param hour the hour-of-day to use, from 0 to 23 1772 * @param minute the minute-of-hour to use, from 0 to 59 1773 * @param second the second-of-minute to represent, from 0 to 59 1774 * @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999 1775 * @return the local date-time formed from this date and the specified time, not null 1776 * @throws DateTimeException if the value of any field is out of range 1777 */ 1778 public LocalDateTime atTime(int hour, int minute, int second, int nanoOfSecond) { 1779 return atTime(LocalTime.of(hour, minute, second, nanoOfSecond)); 1780 } 1781 1782 /** 1783 * Combines this date with an offset time to create an {@code OffsetDateTime}. 1784 * <p> 1785 * This returns an {@code OffsetDateTime} formed from this date at the specified time. 1786 * All possible combinations of date and time are valid. 1787 * 1788 * @param time the time to combine with, not null 1789 * @return the offset date-time formed from this date and the specified time, not null 1790 */ 1791 public OffsetDateTime atTime(OffsetTime time) { 1792 return OffsetDateTime.of(LocalDateTime.of(this, time.toLocalTime()), time.getOffset()); 1793 } 1794 1795 /** 1796 * Combines this date with the time of midnight to create a {@code LocalDateTime} 1797 * at the start of this date. 1798 * <p> 1799 * This returns a {@code LocalDateTime} formed from this date at the time of 1800 * midnight, 00:00, at the start of this date. 1801 * 1802 * @return the local date-time of midnight at the start of this date, not null 1803 */ 1804 public LocalDateTime atStartOfDay() { 1805 return LocalDateTime.of(this, LocalTime.MIDNIGHT); 1806 } 1807 1808 /** 1809 * Returns a zoned date-time from this date at the earliest valid time according 1810 * to the rules in the time-zone. 1811 * <p> 1812 * Time-zone rules, such as daylight savings, mean that not every local date-time 1813 * is valid for the specified zone, thus the local date-time may not be midnight. 1814 * <p> 1815 * In most cases, there is only one valid offset for a local date-time. 1816 * In the case of an overlap, there are two valid offsets, and the earlier one is used, 1817 * corresponding to the first occurrence of midnight on the date. 1818 * In the case of a gap, the zoned date-time will represent the instant just after the gap. 1819 * <p> 1820 * If the zone ID is a {@link ZoneOffset}, then the result always has a time of midnight. 1821 * <p> 1822 * To convert to a specific time in a given time-zone call {@link #atTime(LocalTime)} 1823 * followed by {@link LocalDateTime#atZone(ZoneId)}. 1824 * 1825 * @param zone the zone ID to use, not null 1826 * @return the zoned date-time formed from this date and the earliest valid time for the zone, not null 1827 */ 1828 public ZonedDateTime atStartOfDay(ZoneId zone) { 1829 Objects.requireNonNull(zone, "zone"); 1830 // need to handle case where there is a gap from 11:30 to 00:30 1831 // standard ZDT factory would result in 01:00 rather than 00:30 1832 LocalDateTime ldt = atTime(LocalTime.MIDNIGHT); 1833 if (zone instanceof ZoneOffset == false) { 1834 ZoneRules rules = zone.getRules(); 1835 ZoneOffsetTransition trans = rules.getTransition(ldt); 1836 if (trans != null && trans.isGap()) { 1837 ldt = trans.getDateTimeAfter(); 1838 } 1839 } 1840 return ZonedDateTime.of(ldt, zone); 1841 } 1842 1843 //----------------------------------------------------------------------- 1844 @Override 1845 public long toEpochDay() { 1846 long y = year; 1847 long m = month; 1848 long total = 0; 1849 total += 365 * y; 1850 if (y >= 0) { 1851 total += (y + 3) / 4 - (y + 99) / 100 + (y + 399) / 400; 1852 } else { 1853 total -= y / -4 - y / -100 + y / -400; 1854 } 1855 total += ((367 * m - 362) / 12); 1856 total += day - 1; 1857 if (m > 2) { 1858 total--; 1859 if (isLeapYear() == false) { 1860 total--; 1861 } 1862 } 1863 return total - DAYS_0000_TO_1970; 1864 } 1865 1866 /** 1867 * Converts this {@code LocalDate} to the number of seconds since the epoch 1868 * of 1970-01-01T00:00:00Z. 1869 * <p> 1870 * This returns the number of seconds from the epoch for this {@link LocalDate}. 1871 * 1872 * @param offset the zone offset, not null 1873 * @return the number of seconds since the epoch of 1970-01-01T00:00:00Z, may be negative 1874 */ 1875 public long toEpochSecond(ZoneOffset offset) { 1876 Objects.requireNonNull(offset, "offset"); 1877 long secs = toEpochDay() * SECONDS_PER_DAY; 1878 secs -= offset.getTotalSeconds(); 1879 return secs; 1880 } 1881 1882 //----------------------------------------------------------------------- 1883 /** 1884 * Compares this date to another date. 1885 * <p> 1886 * The comparison is primarily based on the date, from earliest to latest. 1887 * It is "consistent with equals", as defined by {@link Comparable}. 1888 * <p> 1889 * If all the dates being compared are instances of {@code LocalDate}, 1890 * then the comparison will be entirely based on the date. 1891 * If some dates being compared are in different chronologies, then the 1892 * chronology is also considered, see {@link java.time.chrono.ChronoLocalDate#compareTo}. 1893 * 1894 * @param other the other date to compare to, not null 1895 * @return the comparator value, negative if less, positive if greater 1896 */ 1897 @Override // override for Javadoc and performance 1898 public int compareTo(ChronoLocalDate other) { 1899 if (other instanceof LocalDate) { 1900 return compareTo0((LocalDate) other); 1901 } 1902 return ChronoLocalDate.super.compareTo(other); 1903 } 1904 1905 int compareTo0(LocalDate otherDate) { 1906 int cmp = (year - otherDate.year); 1907 if (cmp == 0) { 1908 cmp = (month - otherDate.month); 1909 if (cmp == 0) { 1910 cmp = (day - otherDate.day); 1911 } 1912 } 1913 return cmp; 1914 } 1915 1916 /** 1917 * Checks if this date is after the specified date. 1918 * <p> 1919 * This checks to see if this date represents a point on the 1920 * local time-line after the other date. 1921 * <pre> 1922 * LocalDate a = LocalDate.of(2012, 6, 30); 1923 * LocalDate b = LocalDate.of(2012, 7, 1); 1924 * a.isAfter(b) == false 1925 * a.isAfter(a) == false 1926 * b.isAfter(a) == true 1927 * </pre> 1928 * <p> 1929 * This method only considers the position of the two dates on the local time-line. 1930 * It does not take into account the chronology, or calendar system. 1931 * This is different from the comparison in {@link #compareTo(ChronoLocalDate)}, 1932 * but is the same approach as {@link ChronoLocalDate#timeLineOrder()}. 1933 * 1934 * @param other the other date to compare to, not null 1935 * @return true if this date is after the specified date 1936 */ 1937 @Override // override for Javadoc and performance 1938 public boolean isAfter(ChronoLocalDate other) { 1939 if (other instanceof LocalDate) { 1940 return compareTo0((LocalDate) other) > 0; 1941 } 1942 return ChronoLocalDate.super.isAfter(other); 1943 } 1944 1945 /** 1946 * Checks if this date is before the specified date. 1947 * <p> 1948 * This checks to see if this date represents a point on the 1949 * local time-line before the other date. 1950 * <pre> 1951 * LocalDate a = LocalDate.of(2012, 6, 30); 1952 * LocalDate b = LocalDate.of(2012, 7, 1); 1953 * a.isBefore(b) == true 1954 * a.isBefore(a) == false 1955 * b.isBefore(a) == false 1956 * </pre> 1957 * <p> 1958 * This method only considers the position of the two dates on the local time-line. 1959 * It does not take into account the chronology, or calendar system. 1960 * This is different from the comparison in {@link #compareTo(ChronoLocalDate)}, 1961 * but is the same approach as {@link ChronoLocalDate#timeLineOrder()}. 1962 * 1963 * @param other the other date to compare to, not null 1964 * @return true if this date is before the specified date 1965 */ 1966 @Override // override for Javadoc and performance 1967 public boolean isBefore(ChronoLocalDate other) { 1968 if (other instanceof LocalDate) { 1969 return compareTo0((LocalDate) other) < 0; 1970 } 1971 return ChronoLocalDate.super.isBefore(other); 1972 } 1973 1974 /** 1975 * Checks if this date is equal to the specified date. 1976 * <p> 1977 * This checks to see if this date represents the same point on the 1978 * local time-line as the other date. 1979 * <pre> 1980 * LocalDate a = LocalDate.of(2012, 6, 30); 1981 * LocalDate b = LocalDate.of(2012, 7, 1); 1982 * a.isEqual(b) == false 1983 * a.isEqual(a) == true 1984 * b.isEqual(a) == false 1985 * </pre> 1986 * <p> 1987 * This method only considers the position of the two dates on the local time-line. 1988 * It does not take into account the chronology, or calendar system. 1989 * This is different from the comparison in {@link #compareTo(ChronoLocalDate)} 1990 * but is the same approach as {@link ChronoLocalDate#timeLineOrder()}. 1991 * 1992 * @param other the other date to compare to, not null 1993 * @return true if this date is equal to the specified date 1994 */ 1995 @Override // override for Javadoc and performance 1996 public boolean isEqual(ChronoLocalDate other) { 1997 if (other instanceof LocalDate) { 1998 return compareTo0((LocalDate) other) == 0; 1999 } 2000 return ChronoLocalDate.super.isEqual(other); 2001 } 2002 2003 //----------------------------------------------------------------------- 2004 /** 2005 * Checks if this date is equal to another date. 2006 * <p> 2007 * Compares this {@code LocalDate} with another ensuring that the date is the same. 2008 * <p> 2009 * Only objects of type {@code LocalDate} are compared, other types return false. 2010 * To compare the dates of two {@code TemporalAccessor} instances, including dates 2011 * in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator. 2012 * 2013 * @param obj the object to check, null returns false 2014 * @return true if this is equal to the other date 2015 */ 2016 @Override 2017 public boolean equals(Object obj) { 2018 if (this == obj) { 2019 return true; 2020 } 2021 if (obj instanceof LocalDate) { 2022 return compareTo0((LocalDate) obj) == 0; 2023 } 2024 return false; 2025 } 2026 2027 /** 2028 * A hash code for this date. 2029 * 2030 * @return a suitable hash code 2031 */ 2032 @Override 2033 public int hashCode() { 2034 int yearValue = year; 2035 int monthValue = month; 2036 int dayValue = day; 2037 return (yearValue & 0xFFFFF800) ^ ((yearValue << 11) + (monthValue << 6) + (dayValue)); 2038 } 2039 2040 //----------------------------------------------------------------------- 2041 /** 2042 * Outputs this date as a {@code String}, such as {@code 2007-12-03}. 2043 * <p> 2044 * The output will be in the ISO-8601 format {@code uuuu-MM-dd}. 2045 * 2046 * @return a string representation of this date, not null 2047 */ 2048 @Override 2049 public String toString() { 2050 int yearValue = year; 2051 int monthValue = month; 2052 int dayValue = day; 2053 int absYear = Math.abs(yearValue); 2054 StringBuilder buf = new StringBuilder(10); 2055 if (absYear < 1000) { 2056 if (yearValue < 0) { 2057 buf.append(yearValue - 10000).deleteCharAt(1); 2058 } else { 2059 buf.append(yearValue + 10000).deleteCharAt(0); 2060 } 2061 } else { 2062 if (yearValue > 9999) { 2063 buf.append('+'); 2064 } 2065 buf.append(yearValue); 2066 } 2067 return buf.append(monthValue < 10 ? "-0" : "-") 2068 .append(monthValue) 2069 .append(dayValue < 10 ? "-0" : "-") 2070 .append(dayValue) 2071 .toString(); 2072 } 2073 2074 //----------------------------------------------------------------------- 2075 /** 2076 * Writes the object using a 2077 * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>. 2078 * @serialData 2079 * <pre> 2080 * out.writeByte(3); // identifies a LocalDate 2081 * out.writeInt(year); 2082 * out.writeByte(month); 2083 * out.writeByte(day); 2084 * </pre> 2085 * 2086 * @return the instance of {@code Ser}, not null 2087 */ 2088 private Object writeReplace() { 2089 return new Ser(Ser.LOCAL_DATE_TYPE, this); 2090 } 2091 2092 /** 2093 * Defend against malicious streams. 2094 * 2095 * @param s the stream to read 2096 * @throws InvalidObjectException always 2097 */ 2098 private void readObject(ObjectInputStream s) throws InvalidObjectException { 2099 throw new InvalidObjectException("Deserialization via serialization delegate"); 2100 } 2101 2102 void writeExternal(DataOutput out) throws IOException { 2103 out.writeInt(year); 2104 out.writeByte(month); 2105 out.writeByte(day); 2106 } 2107 2108 static LocalDate readExternal(DataInput in) throws IOException { 2109 int year = in.readInt(); 2110 int month = in.readByte(); 2111 int dayOfMonth = in.readByte(); 2112 return LocalDate.of(year, month, dayOfMonth); 2113 } 2114 2115 }