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