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