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