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