1 /* 2 * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 /* 27 * Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos 28 * 29 * All rights reserved. 30 * 31 * Redistribution and use in source and binary forms, with or without 32 * modification, are permitted provided that the following conditions are met: 33 * 34 * * Redistributions of source code must retain the above copyright notice, 35 * this list of conditions and the following disclaimer. 36 * 37 * * Redistributions in binary form must reproduce the above copyright notice, 38 * this list of conditions and the following disclaimer in the documentation 39 * and/or other materials provided with the distribution. 40 * 41 * * Neither the name of JSR-310 nor the names of its contributors 42 * may be used to endorse or promote products derived from this software 43 * without specific prior written permission. 44 * 45 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 46 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 47 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 48 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 49 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 50 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 51 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 52 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 53 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 54 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 55 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 56 */ 57 package java.time.chrono; 58 59 import static java.time.chrono.ThaiBuddhistChronology.YEARS_DIFFERENCE; 60 import static java.time.temporal.ChronoField.DAY_OF_MONTH; 61 import static java.time.temporal.ChronoField.MONTH_OF_YEAR; 62 import static java.time.temporal.ChronoField.YEAR; 63 64 import java.io.DataInput; 65 import java.io.DataOutput; 66 import java.io.IOException; 67 import java.io.InvalidObjectException; 68 import java.io.ObjectInputStream; 69 import java.io.Serializable; 70 import java.time.Clock; 71 import java.time.DateTimeException; 72 import java.time.LocalDate; 73 import java.time.LocalTime; 74 import java.time.Period; 75 import java.time.ZoneId; 76 import java.time.temporal.ChronoField; 77 import java.time.temporal.TemporalAccessor; 78 import java.time.temporal.TemporalAdjuster; 79 import java.time.temporal.TemporalAmount; 80 import java.time.temporal.TemporalField; 81 import java.time.temporal.TemporalQuery; 82 import java.time.temporal.TemporalUnit; 83 import java.time.temporal.UnsupportedTemporalTypeException; 84 import java.time.temporal.ValueRange; 85 import java.util.Objects; 86 87 /** 88 * A date in the Thai Buddhist calendar system. 89 * <p> 90 * This date operates using the {@linkplain ThaiBuddhistChronology Thai Buddhist calendar}. 91 * This calendar system is primarily used in Thailand. 92 * Dates are aligned such that {@code 2484-01-01 (Buddhist)} is {@code 1941-01-01 (ISO)}. 93 * <p> 94 * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a> 95 * class; programmers should treat instances that are 96 * {@linkplain #equals(Object) equal} as interchangeable and should not 97 * use instances for synchronization, or unpredictable behavior may 98 * occur. For example, in a future release, synchronization may fail. 99 * The {@code equals} method should be used for comparisons. 100 * 101 * @implSpec 102 * This class is immutable and thread-safe. 103 * 104 * @since 1.8 105 */ 106 @jdk.internal.ValueBased 107 @jdk.internal.MigratedValueClass 108 public final class ThaiBuddhistDate 109 extends ChronoLocalDateImpl<ThaiBuddhistDate> 110 implements ChronoLocalDate, Serializable { 111 112 /** 113 * Serialization version. 114 */ 115 @java.io.Serial 116 private static final long serialVersionUID = -8722293800195731463L; 117 118 /** 119 * The underlying date. 120 */ 121 private final transient LocalDate isoDate; 122 123 //----------------------------------------------------------------------- 124 /** 125 * Obtains the current {@code ThaiBuddhistDate} from the system clock in the default time-zone. 126 * <p> 127 * This will query the {@link Clock#systemDefaultZone() system clock} in the default 128 * time-zone to obtain the current date. 129 * <p> 130 * Using this method will prevent the ability to use an alternate clock for testing 131 * because the clock is hard-coded. 132 * 133 * @return the current date using the system clock and default time-zone, not null 134 */ 135 public static ThaiBuddhistDate now() { 136 return now(Clock.systemDefaultZone()); 137 } 138 139 /** 140 * Obtains the current {@code ThaiBuddhistDate} from the system clock in the specified time-zone. 141 * <p> 142 * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date. 143 * Specifying the time-zone avoids dependence on the default time-zone. 144 * <p> 145 * Using this method will prevent the ability to use an alternate clock for testing 146 * because the clock is hard-coded. 147 * 148 * @param zone the zone ID to use, not null 149 * @return the current date using the system clock, not null 150 */ 151 public static ThaiBuddhistDate now(ZoneId zone) { 152 return now(Clock.system(zone)); 153 } 154 155 /** 156 * Obtains the current {@code ThaiBuddhistDate} from the specified clock. 157 * <p> 158 * This will query the specified clock to obtain the current date - today. 159 * Using this method allows the use of an alternate clock for testing. 160 * The alternate clock may be introduced using {@linkplain Clock dependency injection}. 161 * 162 * @param clock the clock to use, not null 163 * @return the current date, not null 164 * @throws DateTimeException if the current date cannot be obtained 165 */ 166 public static ThaiBuddhistDate now(Clock clock) { 167 return new ThaiBuddhistDate(LocalDate.now(clock)); 168 } 169 170 /** 171 * Obtains a {@code ThaiBuddhistDate} representing a date in the Thai Buddhist calendar 172 * system from the proleptic-year, month-of-year and day-of-month fields. 173 * <p> 174 * This returns a {@code ThaiBuddhistDate} with the specified fields. 175 * The day must be valid for the year and month, otherwise an exception will be thrown. 176 * 177 * @param prolepticYear the Thai Buddhist proleptic-year 178 * @param month the Thai Buddhist month-of-year, from 1 to 12 179 * @param dayOfMonth the Thai Buddhist day-of-month, from 1 to 31 180 * @return the date in Thai Buddhist calendar system, not null 181 * @throws DateTimeException if the value of any field is out of range, 182 * or if the day-of-month is invalid for the month-year 183 */ 184 public static ThaiBuddhistDate of(int prolepticYear, int month, int dayOfMonth) { 185 return new ThaiBuddhistDate(LocalDate.of(prolepticYear - YEARS_DIFFERENCE, month, dayOfMonth)); 186 } 187 188 /** 189 * Obtains a {@code ThaiBuddhistDate} from a temporal object. 190 * <p> 191 * This obtains a date in the Thai Buddhist calendar system based on the specified temporal. 192 * A {@code TemporalAccessor} represents an arbitrary set of date and time information, 193 * which this factory converts to an instance of {@code ThaiBuddhistDate}. 194 * <p> 195 * The conversion typically uses the {@link ChronoField#EPOCH_DAY EPOCH_DAY} 196 * field, which is standardized across calendar systems. 197 * <p> 198 * This method matches the signature of the functional interface {@link TemporalQuery} 199 * allowing it to be used as a query via method reference, {@code ThaiBuddhistDate::from}. 200 * 201 * @param temporal the temporal object to convert, not null 202 * @return the date in Thai Buddhist calendar system, not null 203 * @throws DateTimeException if unable to convert to a {@code ThaiBuddhistDate} 204 */ 205 public static ThaiBuddhistDate from(TemporalAccessor temporal) { 206 return ThaiBuddhistChronology.INSTANCE.date(temporal); 207 } 208 209 //----------------------------------------------------------------------- 210 /** 211 * Creates an instance from an ISO date. 212 * 213 * @param isoDate the standard local date, validated not null 214 */ 215 ThaiBuddhistDate(LocalDate isoDate) { 216 Objects.requireNonNull(isoDate, "isoDate"); 217 this.isoDate = isoDate; 218 } 219 220 //----------------------------------------------------------------------- 221 /** 222 * Gets the chronology of this date, which is the Thai Buddhist calendar system. 223 * <p> 224 * The {@code Chronology} represents the calendar system in use. 225 * The era and other fields in {@link ChronoField} are defined by the chronology. 226 * 227 * @return the Thai Buddhist chronology, not null 228 */ 229 @Override 230 public ThaiBuddhistChronology getChronology() { 231 return ThaiBuddhistChronology.INSTANCE; 232 } 233 234 /** 235 * Gets the era applicable at this date. 236 * <p> 237 * The Thai Buddhist calendar system has two eras, 'BE' and 'BEFORE_BE', 238 * defined by {@link ThaiBuddhistEra}. 239 * 240 * @return the era applicable at this date, not null 241 */ 242 @Override 243 public ThaiBuddhistEra getEra() { 244 return (getProlepticYear() >= 1 ? ThaiBuddhistEra.BE : ThaiBuddhistEra.BEFORE_BE); 245 } 246 247 /** 248 * Returns the length of the month represented by this date. 249 * <p> 250 * This returns the length of the month in days. 251 * Month lengths match those of the ISO calendar system. 252 * 253 * @return the length of the month in days 254 */ 255 @Override 256 public int lengthOfMonth() { 257 return isoDate.lengthOfMonth(); 258 } 259 260 //----------------------------------------------------------------------- 261 @Override 262 public ValueRange range(TemporalField field) { 263 if (field instanceof ChronoField) { 264 if (isSupported(field)) { 265 ChronoField f = (ChronoField) field; 266 switch (f) { 267 case DAY_OF_MONTH: 268 case DAY_OF_YEAR: 269 case ALIGNED_WEEK_OF_MONTH: 270 return isoDate.range(field); 271 case YEAR_OF_ERA: { 272 ValueRange range = YEAR.range(); 273 long max = (getProlepticYear() <= 0 ? -(range.getMinimum() + YEARS_DIFFERENCE) + 1 : range.getMaximum() + YEARS_DIFFERENCE); 274 return ValueRange.of(1, max); 275 } 276 } 277 return getChronology().range(f); 278 } 279 throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 280 } 281 return field.rangeRefinedBy(this); 282 } 283 284 @Override 285 public long getLong(TemporalField field) { 286 if (field instanceof ChronoField) { 287 switch ((ChronoField) field) { 288 case PROLEPTIC_MONTH: 289 return getProlepticMonth(); 290 case YEAR_OF_ERA: { 291 int prolepticYear = getProlepticYear(); 292 return (prolepticYear >= 1 ? prolepticYear : 1 - prolepticYear); 293 } 294 case YEAR: 295 return getProlepticYear(); 296 case ERA: 297 return (getProlepticYear() >= 1 ? 1 : 0); 298 } 299 return isoDate.getLong(field); 300 } 301 return field.getFrom(this); 302 } 303 304 private long getProlepticMonth() { 305 return getProlepticYear() * 12L + isoDate.getMonthValue() - 1; 306 } 307 308 private int getProlepticYear() { 309 return isoDate.getYear() + YEARS_DIFFERENCE; 310 } 311 312 //----------------------------------------------------------------------- 313 @Override 314 public ThaiBuddhistDate with(TemporalField field, long newValue) { 315 if (field instanceof ChronoField chronoField) { 316 if (getLong(chronoField) == newValue) { 317 return this; 318 } 319 switch (chronoField) { 320 case PROLEPTIC_MONTH: 321 getChronology().range(chronoField).checkValidValue(newValue, chronoField); 322 return plusMonths(newValue - getProlepticMonth()); 323 case YEAR_OF_ERA: 324 case YEAR: 325 case ERA: { 326 int nvalue = getChronology().range(chronoField).checkValidIntValue(newValue, chronoField); 327 switch (chronoField) { 328 case YEAR_OF_ERA: 329 return with(isoDate.withYear((getProlepticYear() >= 1 ? nvalue : 1 - nvalue) - YEARS_DIFFERENCE)); 330 case YEAR: 331 return with(isoDate.withYear(nvalue - YEARS_DIFFERENCE)); 332 case ERA: 333 return with(isoDate.withYear((1 - getProlepticYear()) - YEARS_DIFFERENCE)); 334 } 335 } 336 } 337 return with(isoDate.with(field, newValue)); 338 } 339 return super.with(field, newValue); 340 } 341 342 /** 343 * {@inheritDoc} 344 * @throws DateTimeException {@inheritDoc} 345 * @throws ArithmeticException {@inheritDoc} 346 */ 347 @Override 348 public ThaiBuddhistDate with(TemporalAdjuster adjuster) { 349 return super.with(adjuster); 350 } 351 352 /** 353 * {@inheritDoc} 354 * @throws DateTimeException {@inheritDoc} 355 * @throws ArithmeticException {@inheritDoc} 356 */ 357 @Override 358 public ThaiBuddhistDate plus(TemporalAmount amount) { 359 return super.plus(amount); 360 } 361 362 /** 363 * {@inheritDoc} 364 * @throws DateTimeException {@inheritDoc} 365 * @throws ArithmeticException {@inheritDoc} 366 */ 367 @Override 368 public ThaiBuddhistDate minus(TemporalAmount amount) { 369 return super.minus(amount); 370 } 371 372 //----------------------------------------------------------------------- 373 @Override 374 ThaiBuddhistDate plusYears(long years) { 375 return with(isoDate.plusYears(years)); 376 } 377 378 @Override 379 ThaiBuddhistDate plusMonths(long months) { 380 return with(isoDate.plusMonths(months)); 381 } 382 383 @Override 384 ThaiBuddhistDate plusWeeks(long weeksToAdd) { 385 return super.plusWeeks(weeksToAdd); 386 } 387 388 @Override 389 ThaiBuddhistDate plusDays(long days) { 390 return with(isoDate.plusDays(days)); 391 } 392 393 @Override 394 public ThaiBuddhistDate plus(long amountToAdd, TemporalUnit unit) { 395 return super.plus(amountToAdd, unit); 396 } 397 398 @Override 399 public ThaiBuddhistDate minus(long amountToSubtract, TemporalUnit unit) { 400 return super.minus(amountToSubtract, unit); 401 } 402 403 @Override 404 ThaiBuddhistDate minusYears(long yearsToSubtract) { 405 return super.minusYears(yearsToSubtract); 406 } 407 408 @Override 409 ThaiBuddhistDate minusMonths(long monthsToSubtract) { 410 return super.minusMonths(monthsToSubtract); 411 } 412 413 @Override 414 ThaiBuddhistDate minusWeeks(long weeksToSubtract) { 415 return super.minusWeeks(weeksToSubtract); 416 } 417 418 @Override 419 ThaiBuddhistDate minusDays(long daysToSubtract) { 420 return super.minusDays(daysToSubtract); 421 } 422 423 private ThaiBuddhistDate with(LocalDate newDate) { 424 return (newDate.equals(isoDate) ? this : new ThaiBuddhistDate(newDate)); 425 } 426 427 @Override // for javadoc and covariant return type 428 @SuppressWarnings("unchecked") 429 public final ChronoLocalDateTime<ThaiBuddhistDate> atTime(LocalTime localTime) { 430 return (ChronoLocalDateTime<ThaiBuddhistDate>) super.atTime(localTime); 431 } 432 433 @Override 434 public ChronoPeriod until(ChronoLocalDate endDate) { 435 Period period = isoDate.until(endDate); 436 return getChronology().period(period.getYears(), period.getMonths(), period.getDays()); 437 } 438 439 @Override // override for performance 440 public long toEpochDay() { 441 return isoDate.toEpochDay(); 442 } 443 444 //------------------------------------------------------------------------- 445 /** 446 * Compares this date to another date, including the chronology. 447 * <p> 448 * Compares this {@code ThaiBuddhistDate} with another ensuring that the date is the same. 449 * <p> 450 * Only objects of type {@code ThaiBuddhistDate} are compared, other types return false. 451 * To compare the dates of two {@code TemporalAccessor} instances, including dates 452 * in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator. 453 * 454 * @param obj the object to check, null returns false 455 * @return true if this is equal to the other date 456 */ 457 @Override // override for performance 458 public boolean equals(Object obj) { 459 if (this == obj) { 460 return true; 461 } 462 return (obj instanceof ThaiBuddhistDate otherDate) 463 && this.isoDate.equals(otherDate.isoDate); 464 } 465 466 /** 467 * A hash code for this date. 468 * 469 * @return a suitable hash code based only on the Chronology and the date 470 */ 471 @Override // override for performance 472 public int hashCode() { 473 return getChronology().getId().hashCode() ^ isoDate.hashCode(); 474 } 475 476 //----------------------------------------------------------------------- 477 /** 478 * Defend against malicious streams. 479 * 480 * @param s the stream to read 481 * @throws InvalidObjectException always 482 */ 483 @java.io.Serial 484 private void readObject(ObjectInputStream s) throws InvalidObjectException { 485 throw new InvalidObjectException("Deserialization via serialization delegate"); 486 } 487 488 /** 489 * Writes the object using a 490 * <a href="{@docRoot}/serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>. 491 * @serialData 492 * <pre> 493 * out.writeByte(10); // identifies a ThaiBuddhistDate 494 * out.writeInt(get(YEAR)); 495 * out.writeByte(get(MONTH_OF_YEAR)); 496 * out.writeByte(get(DAY_OF_MONTH)); 497 * </pre> 498 * 499 * @return the instance of {@code Ser}, not null 500 */ 501 @java.io.Serial 502 private Object writeReplace() { 503 return new Ser(Ser.THAIBUDDHIST_DATE_TYPE, this); 504 } 505 506 void writeExternal(DataOutput out) throws IOException { 507 // ThaiBuddhistChronology is implicit in the THAIBUDDHIST_DATE_TYPE 508 out.writeInt(this.get(YEAR)); 509 out.writeByte(this.get(MONTH_OF_YEAR)); 510 out.writeByte(this.get(DAY_OF_MONTH)); 511 } 512 513 static ThaiBuddhistDate readExternal(DataInput in) throws IOException { 514 int year = in.readInt(); 515 int month = in.readByte(); 516 int dayOfMonth = in.readByte(); 517 return ThaiBuddhistChronology.INSTANCE.date(year, month, dayOfMonth); 518 } 519 520 }