1 /* 2 * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 /* 27 * 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.temporal.ChronoField.DAY_OF_MONTH; 60 import static java.time.temporal.ChronoField.MONTH_OF_YEAR; 61 import static java.time.temporal.ChronoField.YEAR; 62 63 import java.io.DataInput; 64 import java.io.DataOutput; 65 import java.io.IOException; 66 import java.io.Serializable; 67 import java.time.Clock; 68 import java.time.DateTimeException; 69 import java.time.LocalDate; 70 import java.time.LocalTime; 71 import java.time.Period; 72 import java.time.ZoneId; 73 import java.time.temporal.ChronoField; 74 import java.time.temporal.TemporalQuery; 75 import java.time.temporal.TemporalAccessor; 76 import java.time.temporal.TemporalAdjuster; 77 import java.time.temporal.TemporalAmount; 78 import java.time.temporal.TemporalField; 79 import java.time.temporal.TemporalUnit; 80 import java.time.temporal.ValueRange; 81 import java.util.Calendar; 82 import java.util.Objects; 83 84 import sun.util.calendar.LocalGregorianCalendar; 85 86 /** 87 * A date in the Japanese Imperial calendar system. 88 * <p> 89 * This date operates using the {@linkplain JapaneseChronology Japanese Imperial calendar}. 90 * This calendar system is primarily used in Japan. 91 * <p> 92 * The Japanese Imperial calendar system is the same as the ISO calendar system 93 * apart from the era-based year numbering. The proleptic-year is defined to be 94 * equal to the ISO proleptic-year. 95 * <p> 96 * For example, the Japanese year "Heisei 24" corresponds to ISO year "2012".<br> 97 * Calling {@code japaneseDate.get(YEAR_OF_ERA)} will return 24.<br> 98 * Calling {@code japaneseDate.get(YEAR)} will return 2012.<br> 99 * Calling {@code japaneseDate.get(ERA)} will return 2, corresponding to 100 * {@code JapaneseChronology.ERA_HEISEI}.<br> 101 * 102 * <h3>Specification for implementors</h3> 103 * This class is immutable and thread-safe. 104 * 105 * @since 1.8 106 */ 107 public final class JapaneseDate 108 extends ChronoDateImpl<JapaneseDate> 109 implements ChronoLocalDate<JapaneseDate>, Serializable { 110 111 /** 112 * Serialization version. 113 */ 114 private static final long serialVersionUID = -305327627230580483L; 115 116 /** 117 * The underlying ISO local date. 118 */ 119 private transient final LocalDate isoDate; 120 /** 121 * The JapaneseEra of this date. 122 */ 123 private transient JapaneseEra era; 124 /** 125 * The Japanese imperial calendar year of this date. 126 */ 127 private transient int yearOfEra; 128 129 //----------------------------------------------------------------------- 130 /** 131 * Obtains the current {@code JapaneseDate} from the system clock in the default time-zone. 132 * <p> 133 * This will query the {@link Clock#systemDefaultZone() system clock} in the default 134 * time-zone to obtain the current date. 135 * <p> 136 * Using this method will prevent the ability to use an alternate clock for testing 137 * because the clock is hard-coded. 138 * 139 * @return the current date using the system clock and default time-zone, not null 140 */ 141 public static JapaneseDate now() { 142 return now(Clock.systemDefaultZone()); 143 } 144 145 /** 146 * Obtains the current {@code JapaneseDate} from the system clock in the specified time-zone. 147 * <p> 148 * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date. 149 * Specifying the time-zone avoids dependence on the default time-zone. 150 * <p> 151 * Using this method will prevent the ability to use an alternate clock for testing 152 * because the clock is hard-coded. 153 * 154 * @param zone the zone ID to use, not null 155 * @return the current date using the system clock, not null 156 */ 157 public static JapaneseDate now(ZoneId zone) { 158 return now(Clock.system(zone)); 159 } 160 161 /** 162 * Obtains the current {@code JapaneseDate} from the specified clock. 163 * <p> 164 * This will query the specified clock to obtain the current date - today. 165 * Using this method allows the use of an alternate clock for testing. 166 * The alternate clock may be introduced using {@linkplain Clock dependency injection}. 167 * 168 * @param clock the clock to use, not null 169 * @return the current date, not null 170 * @throws DateTimeException if the current date cannot be obtained 171 */ 172 public static JapaneseDate now(Clock clock) { 173 return JapaneseChronology.INSTANCE.date(LocalDate.now(clock)); 174 } 175 176 /** 177 * Obtains a {@code JapaneseDate} representing a date in the Japanese calendar 178 * system from the era, year-of-era, month-of-year and day-of-month fields. 179 * <p> 180 * This returns a {@code JapaneseDate} with the specified fields. 181 * The day must be valid for the year and month, otherwise an exception will be thrown. 182 * 183 * @param era the Japanese era, not null 184 * @param yearOfEra the Japanese year-of-era 185 * @param month the Japanese month-of-year, from 1 to 12 186 * @param dayOfMonth the Japanese day-of-month, from 1 to 31 187 * @return the date in Japanese calendar system, not null 188 * @throws DateTimeException if the value of any field is out of range, 189 * or if the day-of-month is invalid for the month-year, 190 * or if the date is not a Japanese era 191 */ 192 public static JapaneseDate of(Era era, int yearOfEra, int month, int dayOfMonth) { 193 if (era instanceof JapaneseEra == false) { 194 throw new DateTimeException("Era must be JapaneseEra"); 195 } 196 return JapaneseDate.of((JapaneseEra) era, yearOfEra, month, dayOfMonth); 197 } 198 199 /** 200 * Obtains a {@code JapaneseDate} representing a date in the Japanese calendar 201 * system from the proleptic-year, month-of-year and day-of-month fields. 202 * <p> 203 * This returns a {@code JapaneseDate} with the specified fields. 204 * The day must be valid for the year and month, otherwise an exception will be thrown. 205 * 206 * @param prolepticYear the Japanese proleptic-year 207 * @param month the Japanese month-of-year, from 1 to 12 208 * @param dayOfMonth the Japanese day-of-month, from 1 to 31 209 * @return the date in Japanese calendar system, not null 210 * @throws DateTimeException if the value of any field is out of range, 211 * or if the day-of-month is invalid for the month-year 212 */ 213 public static JapaneseDate of(int prolepticYear, int month, int dayOfMonth) { 214 return new JapaneseDate(LocalDate.of(prolepticYear, month, dayOfMonth)); 215 } 216 217 /** 218 * Obtains a {@code JapaneseDate} representing a date in the Japanese calendar 219 * system from the proleptic-year and day-of-year fields. 220 * <p> 221 * This returns a {@code JapaneseDate} with the specified fields. 222 * The day must be valid for the year, otherwise an exception will be thrown. 223 * 224 * @param prolepticYear the chronology proleptic-year 225 * @param dayOfYear the chronology day-of-year, from 1 to 366 226 * @return the date in Japanese calendar system, not null 227 * @throws DateTimeException if the value of any field is out of range, 228 * or if the day-of-year is invalid for the year 229 */ 230 public static JapaneseDate ofYearDay(int prolepticYear, int dayOfYear) { 231 LocalDate date = LocalDate.ofYearDay(prolepticYear, dayOfYear); 232 return of(prolepticYear, date.getMonthValue(), date.getDayOfMonth()); 233 } 234 235 /** 236 * Obtains a {@code JapaneseDate} representing a date in the Japanese calendar 237 * system from the era, year-of-era, month-of-year and day-of-month fields. 238 * <p> 239 * This returns a {@code JapaneseDate} with the specified fields. 240 * The day must be valid for the year and month, otherwise an exception will be thrown. 241 * 242 * @param era the Japanese era, not null 243 * @param yearOfEra the Japanese year-of-era 244 * @param month the Japanese month-of-year, from 1 to 12 245 * @param dayOfMonth the Japanese day-of-month, from 1 to 31 246 * @return the date in Japanese calendar system, 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 JapaneseDate of(JapaneseEra era, int yearOfEra, int month, int dayOfMonth) { 251 Objects.requireNonNull(era, "era"); 252 LocalGregorianCalendar.Date jdate = JapaneseChronology.JCAL.newCalendarDate(null); 253 jdate.setEra(era.getPrivateEra()).setDate(yearOfEra, month, dayOfMonth); 254 if (!JapaneseChronology.JCAL.validate(jdate)) { 255 throw new IllegalArgumentException(); 256 } 257 LocalDate date = LocalDate.of(jdate.getNormalizedYear(), month, dayOfMonth); 258 return new JapaneseDate(era, yearOfEra, date); 259 } 260 261 /** 262 * Obtains a {@code JapaneseDate} from a temporal object. 263 * <p> 264 * This obtains a date in the Japanese calendar system based on the specified temporal. 265 * A {@code TemporalAccessor} represents an arbitrary set of date and time information, 266 * which this factory converts to an instance of {@code JapaneseDate}. 267 * <p> 268 * The conversion typically uses the {@link ChronoField#EPOCH_DAY EPOCH_DAY} 269 * field, which is standardized across calendar systems. 270 * <p> 271 * This method matches the signature of the functional interface {@link TemporalQuery} 272 * allowing it to be used as a query via method reference, {@code JapaneseDate::from}. 273 * 274 * @param temporal the temporal object to convert, not null 275 * @return the date in Japanese calendar system, not null 276 * @throws DateTimeException if unable to convert to a {@code JapaneseDate} 277 */ 278 public static JapaneseDate from(TemporalAccessor temporal) { 279 return JapaneseChronology.INSTANCE.date(temporal); 280 } 281 282 //----------------------------------------------------------------------- 283 /** 284 * Creates an instance from an ISO date. 285 * 286 * @param isoDate the standard local date, validated not null 287 */ 288 JapaneseDate(LocalDate isoDate) { 289 LocalGregorianCalendar.Date jdate = toPrivateJapaneseDate(isoDate); 290 this.era = JapaneseEra.toJapaneseEra(jdate.getEra()); 291 this.yearOfEra = jdate.getYear(); 292 this.isoDate = isoDate; 293 } 294 295 /** 296 * Constructs a {@code JapaneseDate}. This constructor does NOT validate the given parameters, 297 * and {@code era} and {@code year} must agree with {@code isoDate}. 298 * 299 * @param era the era, validated not null 300 * @param year the year-of-era, validated 301 * @param isoDate the standard local date, validated not null 302 */ 303 JapaneseDate(JapaneseEra era, int year, LocalDate isoDate) { 304 this.era = era; 305 this.yearOfEra = year; 306 this.isoDate = isoDate; 307 } 308 309 //----------------------------------------------------------------------- 310 @Override 311 public JapaneseChronology getChronology() { 312 return JapaneseChronology.INSTANCE; 313 } 314 315 @Override 316 public int lengthOfMonth() { 317 return isoDate.lengthOfMonth(); 318 } 319 320 @Override 321 public ValueRange range(TemporalField field) { 322 if (field instanceof ChronoField) { 323 if (isSupported(field)) { 324 ChronoField f = (ChronoField) field; 325 switch (f) { 326 case DAY_OF_YEAR: 327 return actualRange(Calendar.DAY_OF_YEAR); 328 case YEAR_OF_ERA: 329 return actualRange(Calendar.YEAR); 330 } 331 return getChronology().range(f); 332 } 333 throw new DateTimeException("Unsupported field: " + field.getName()); 334 } 335 return field.rangeRefinedBy(this); 336 } 337 338 private ValueRange actualRange(int calendarField) { 339 Calendar jcal = Calendar.getInstance(JapaneseChronology.LOCALE); 340 jcal.set(Calendar.ERA, era.getValue() + JapaneseEra.ERA_OFFSET); 341 jcal.set(yearOfEra, isoDate.getMonthValue() - 1, isoDate.getDayOfMonth()); 342 return ValueRange.of(jcal.getActualMinimum(calendarField), 343 jcal.getActualMaximum(calendarField)); 344 } 345 346 @Override 347 public long getLong(TemporalField field) { 348 if (field instanceof ChronoField) { 349 switch ((ChronoField) field) { 350 case YEAR_OF_ERA: 351 return yearOfEra; 352 case ERA: 353 return era.getValue(); 354 case DAY_OF_YEAR: { 355 LocalGregorianCalendar.Date jdate = toPrivateJapaneseDate(isoDate); 356 return JapaneseChronology.JCAL.getDayOfYear(jdate); 357 } 358 } 359 // TODO: review other fields 360 return isoDate.getLong(field); 361 } 362 return field.getFrom(this); 363 } 364 365 /** 366 * Returns a {@code LocalGregorianCalendar.Date} converted from the given {@code isoDate}. 367 * 368 * @param isoDate the local date, not null 369 * @return a {@code LocalGregorianCalendar.Date}, not null 370 */ 371 private static LocalGregorianCalendar.Date toPrivateJapaneseDate(LocalDate isoDate) { 372 LocalGregorianCalendar.Date jdate = JapaneseChronology.JCAL.newCalendarDate(null); 373 sun.util.calendar.Era sunEra = JapaneseEra.privateEraFrom(isoDate); 374 int year = isoDate.getYear(); 375 if (sunEra != null) { 376 year -= sunEra.getSinceDate().getYear() - 1; 377 } 378 jdate.setEra(sunEra).setYear(year).setMonth(isoDate.getMonthValue()).setDayOfMonth(isoDate.getDayOfMonth()); 379 JapaneseChronology.JCAL.normalize(jdate); 380 return jdate; 381 } 382 383 //----------------------------------------------------------------------- 384 @Override 385 public JapaneseDate with(TemporalField field, long newValue) { 386 if (field instanceof ChronoField) { 387 ChronoField f = (ChronoField) field; 388 if (getLong(f) == newValue) { 389 return this; 390 } 391 switch (f) { 392 case YEAR_OF_ERA: 393 case YEAR: 394 case ERA: { 395 f.checkValidValue(newValue); 396 int nvalue = (int) newValue; 397 switch (f) { 398 case YEAR_OF_ERA: 399 return this.withYear(nvalue); 400 case YEAR: 401 return with(isoDate.withYear(nvalue)); 402 case ERA: { 403 return this.withYear(JapaneseEra.of(nvalue), yearOfEra); 404 } 405 } 406 } 407 } 408 // TODO: review other fields, such as WEEK_OF_YEAR 409 return with(isoDate.with(field, newValue)); 410 } 411 return (JapaneseDate) ChronoLocalDate.super.with(field, newValue); 412 } 413 414 @Override 415 public Era getEra() { 416 return era; 417 } 418 419 /** 420 * {@inheritDoc} 421 * @throws DateTimeException {@inheritDoc} 422 * @throws ArithmeticException {@inheritDoc} 423 */ 424 @Override 425 public JapaneseDate with(TemporalAdjuster adjuster) { 426 return (JapaneseDate)super.with(adjuster); 427 } 428 429 /** 430 * {@inheritDoc} 431 * @throws DateTimeException {@inheritDoc} 432 * @throws ArithmeticException {@inheritDoc} 433 */ 434 @Override 435 public JapaneseDate plus(TemporalAmount amount) { 436 return (JapaneseDate)super.plus(amount); 437 } 438 439 /** 440 * {@inheritDoc} 441 * @throws DateTimeException {@inheritDoc} 442 * @throws ArithmeticException {@inheritDoc} 443 */ 444 @Override 445 public JapaneseDate minus(TemporalAmount amount) { 446 return (JapaneseDate)super.minus(amount); 447 } 448 //----------------------------------------------------------------------- 449 /** 450 * Returns a copy of this date with the year altered. 451 * <p> 452 * This method changes the year of the date. 453 * If the month-day is invalid for the year, then the previous valid day 454 * will be selected instead. 455 * <p> 456 * This instance is immutable and unaffected by this method call. 457 * 458 * @param era the era to set in the result, not null 459 * @param yearOfEra the year-of-era to set in the returned date 460 * @return a {@code JapaneseDate} based on this date with the requested year, never null 461 * @throws DateTimeException if {@code year} is invalid 462 */ 463 private JapaneseDate withYear(JapaneseEra era, int yearOfEra) { 464 int year = JapaneseChronology.INSTANCE.prolepticYear(era, yearOfEra); 465 return with(isoDate.withYear(year)); 466 } 467 468 /** 469 * Returns a copy of this date with the year-of-era altered. 470 * <p> 471 * This method changes the year-of-era of the date. 472 * If the month-day is invalid for the year, then the previous valid day 473 * will be selected instead. 474 * <p> 475 * This instance is immutable and unaffected by this method call. 476 * 477 * @param year the year to set in the returned date 478 * @return a {@code JapaneseDate} based on this date with the requested year-of-era, never null 479 * @throws DateTimeException if {@code year} is invalid 480 */ 481 private JapaneseDate withYear(int year) { 482 return withYear((JapaneseEra) getEra(), year); 483 } 484 485 //----------------------------------------------------------------------- 486 @Override 487 JapaneseDate plusYears(long years) { 488 return with(isoDate.plusYears(years)); 489 } 490 491 @Override 492 JapaneseDate plusMonths(long months) { 493 return with(isoDate.plusMonths(months)); 494 } 495 496 @Override 497 JapaneseDate plusWeeks(long weeksToAdd) { 498 return with(isoDate.plusWeeks(weeksToAdd)); 499 } 500 501 @Override 502 JapaneseDate plusDays(long days) { 503 return with(isoDate.plusDays(days)); 504 } 505 506 @Override 507 public JapaneseDate plus(long amountToAdd, TemporalUnit unit) { 508 return (JapaneseDate)super.plus(amountToAdd, unit); 509 } 510 511 @Override 512 public JapaneseDate minus(long amountToAdd, TemporalUnit unit) { 513 return (JapaneseDate)super.minus(amountToAdd, unit); 514 } 515 516 @Override 517 JapaneseDate minusYears(long yearsToSubtract) { 518 return (JapaneseDate)super.minusYears(yearsToSubtract); 519 } 520 521 @Override 522 JapaneseDate minusMonths(long monthsToSubtract) { 523 return (JapaneseDate)super.minusMonths(monthsToSubtract); 524 } 525 526 @Override 527 JapaneseDate minusWeeks(long weeksToSubtract) { 528 return (JapaneseDate)super.minusWeeks(weeksToSubtract); 529 } 530 531 @Override 532 JapaneseDate minusDays(long daysToSubtract) { 533 return (JapaneseDate)super.minusDays(daysToSubtract); 534 } 535 536 private JapaneseDate with(LocalDate newDate) { 537 return (newDate.equals(isoDate) ? this : new JapaneseDate(newDate)); 538 } 539 540 @Override // for javadoc and covariant return type 541 public final ChronoLocalDateTime<JapaneseDate> atTime(LocalTime localTime) { 542 return (ChronoLocalDateTime<JapaneseDate>)super.atTime(localTime); 543 } 544 545 @Override 546 public Period periodUntil(ChronoLocalDate<?> endDate) { 547 return isoDate.periodUntil(endDate); 548 } 549 550 @Override // override for performance 551 public long toEpochDay() { 552 return isoDate.toEpochDay(); 553 } 554 555 //------------------------------------------------------------------------- 556 @Override // override for performance 557 public boolean equals(Object obj) { 558 if (this == obj) { 559 return true; 560 } 561 if (obj instanceof JapaneseDate) { 562 JapaneseDate otherDate = (JapaneseDate) obj; 563 return this.isoDate.equals(otherDate.isoDate); 564 } 565 return false; 566 } 567 568 @Override // override for performance 569 public int hashCode() { 570 return getChronology().getId().hashCode() ^ isoDate.hashCode(); 571 } 572 573 @Override 574 public String toString() { 575 if (era == JapaneseEra.SEIREKI) { 576 return getChronology().getId() + " " + isoDate.toString(); 577 } 578 return super.toString(); 579 } 580 581 //----------------------------------------------------------------------- 582 private Object writeReplace() { 583 return new Ser(Ser.JAPANESE_DATE_TYPE, this); 584 } 585 586 void writeExternal(DataOutput out) throws IOException { 587 // JapaneseChronology is implicit in the JAPANESE_DATE_TYPE 588 out.writeInt(get(YEAR)); 589 out.writeByte(get(MONTH_OF_YEAR)); 590 out.writeByte(get(DAY_OF_MONTH)); 591 } 592 593 static JapaneseDate readExternal(DataInput in) throws IOException { 594 int year = in.readInt(); 595 int month = in.readByte(); 596 int dayOfMonth = in.readByte(); 597 return JapaneseChronology.INSTANCE.date(year, month, dayOfMonth); 598 } 599 600 }