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