Path: blob/master/src/java.base/share/classes/java/time/chrono/JapaneseChronology.java
41159 views
/*1* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos27*28* All rights reserved.29*30* Redistribution and use in source and binary forms, with or without31* modification, are permitted provided that the following conditions are met:32*33* * Redistributions of source code must retain the above copyright notice,34* this list of conditions and the following disclaimer.35*36* * Redistributions in binary form must reproduce the above copyright notice,37* this list of conditions and the following disclaimer in the documentation38* and/or other materials provided with the distribution.39*40* * Neither the name of JSR-310 nor the names of its contributors41* may be used to endorse or promote products derived from this software42* without specific prior written permission.43*44* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS45* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT46* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR47* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR48* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,49* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,50* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR51* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF52* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING53* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS54* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.55*/56package java.time.chrono;5758import static java.time.temporal.ChronoField.DAY_OF_MONTH;59import static java.time.temporal.ChronoField.DAY_OF_YEAR;60import static java.time.temporal.ChronoField.ERA;61import static java.time.temporal.ChronoField.MONTH_OF_YEAR;62import static java.time.temporal.ChronoField.YEAR;63import static java.time.temporal.ChronoField.YEAR_OF_ERA;64import static java.time.temporal.ChronoUnit.DAYS;65import static java.time.temporal.ChronoUnit.MONTHS;6667import java.io.InvalidObjectException;68import java.io.ObjectInputStream;69import java.io.Serializable;70import java.time.Clock;71import java.time.DateTimeException;72import java.time.Instant;73import java.time.LocalDate;74import java.time.Year;75import java.time.ZoneId;76import java.time.format.ResolverStyle;77import java.time.temporal.ChronoField;78import java.time.temporal.TemporalAccessor;79import java.time.temporal.TemporalAdjusters;80import java.time.temporal.TemporalField;81import java.time.temporal.UnsupportedTemporalTypeException;82import java.time.temporal.ValueRange;83import java.util.Calendar;84import java.util.List;85import java.util.Locale;86import java.util.Map;8788import sun.util.calendar.CalendarSystem;89import sun.util.calendar.LocalGregorianCalendar;9091/**92* The Japanese Imperial calendar system.93* <p>94* This chronology defines the rules of the Japanese Imperial calendar system.95* This calendar system is primarily used in Japan.96* The Japanese Imperial calendar system is the same as the ISO calendar system97* apart from the era-based year numbering.98* <p>99* Japan introduced the Gregorian calendar starting with Meiji 6.100* Only Meiji and later eras are supported;101* dates before Meiji 6, January 1 are not supported.102* <p>103* The supported {@code ChronoField} instances are:104* <ul>105* <li>{@code DAY_OF_WEEK}106* <li>{@code DAY_OF_MONTH}107* <li>{@code DAY_OF_YEAR}108* <li>{@code EPOCH_DAY}109* <li>{@code MONTH_OF_YEAR}110* <li>{@code PROLEPTIC_MONTH}111* <li>{@code YEAR_OF_ERA}112* <li>{@code YEAR}113* <li>{@code ERA}114* </ul>115*116* @implSpec117* This class is immutable and thread-safe.118*119* @since 1.8120*/121public final class JapaneseChronology extends AbstractChronology implements Serializable {122123static final LocalGregorianCalendar JCAL =124(LocalGregorianCalendar) CalendarSystem.forName("japanese");125126// Locale for creating a JapaneseImpericalCalendar.127static final Locale LOCALE = Locale.forLanguageTag("ja-JP-u-ca-japanese");128129/**130* Singleton instance for Japanese chronology.131*/132public static final JapaneseChronology INSTANCE = new JapaneseChronology();133134/**135* Serialization version.136*/137@java.io.Serial138private static final long serialVersionUID = 459996390165777884L;139140//-----------------------------------------------------------------------141/**142* Restricted constructor.143*/144private JapaneseChronology() {145}146147//-----------------------------------------------------------------------148/**149* Gets the ID of the chronology - 'Japanese'.150* <p>151* The ID uniquely identifies the {@code Chronology}.152* It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.153*154* @return the chronology ID - 'Japanese'155* @see #getCalendarType()156*/157@Override158public String getId() {159return "Japanese";160}161162/**163* Gets the calendar type of the underlying calendar system - 'japanese'.164* <p>165* The calendar type is an identifier defined by the166* <em>Unicode Locale Data Markup Language (LDML)</em> specification.167* It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.168* It can also be used as part of a locale, accessible via169* {@link Locale#getUnicodeLocaleType(String)} with the key 'ca'.170*171* @return the calendar system type - 'japanese'172* @see #getId()173*/174@Override175public String getCalendarType() {176return "japanese";177}178179//-----------------------------------------------------------------------180/**181* Obtains a local date in Japanese calendar system from the182* era, year-of-era, month-of-year and day-of-month fields.183* <p>184* The Japanese month and day-of-month are the same as those in the185* ISO calendar system. They are not reset when the era changes.186* For example:187* <pre>188* 6th Jan Showa 64 = ISO 1989-01-06189* 7th Jan Showa 64 = ISO 1989-01-07190* 8th Jan Heisei 1 = ISO 1989-01-08191* 9th Jan Heisei 1 = ISO 1989-01-09192* </pre>193*194* @param era the Japanese era, not null195* @param yearOfEra the year-of-era196* @param month the month-of-year197* @param dayOfMonth the day-of-month198* @return the Japanese local date, not null199* @throws DateTimeException if unable to create the date200* @throws ClassCastException if the {@code era} is not a {@code JapaneseEra}201*/202@Override203public JapaneseDate date(Era era, int yearOfEra, int month, int dayOfMonth) {204if (!(era instanceof JapaneseEra jera)) {205throw new ClassCastException("Era must be JapaneseEra");206}207return JapaneseDate.of(jera, yearOfEra, month, dayOfMonth);208}209210/**211* Obtains a local date in Japanese calendar system from the212* proleptic-year, month-of-year and day-of-month fields.213* <p>214* The Japanese proleptic year, month and day-of-month are the same as those215* in the ISO calendar system. They are not reset when the era changes.216*217* @param prolepticYear the proleptic-year218* @param month the month-of-year219* @param dayOfMonth the day-of-month220* @return the Japanese local date, not null221* @throws DateTimeException if unable to create the date222*/223@Override224public JapaneseDate date(int prolepticYear, int month, int dayOfMonth) {225return new JapaneseDate(LocalDate.of(prolepticYear, month, dayOfMonth));226}227228/**229* Obtains a local date in Japanese calendar system from the230* era, year-of-era and day-of-year fields.231* <p>232* The day-of-year in this factory is expressed relative to the start of the year-of-era.233* This definition changes the normal meaning of day-of-year only in those years234* where the year-of-era is reset to one due to a change in the era.235* For example:236* <pre>237* 6th Jan Showa 64 = day-of-year 6238* 7th Jan Showa 64 = day-of-year 7239* 8th Jan Heisei 1 = day-of-year 1240* 9th Jan Heisei 1 = day-of-year 2241* </pre>242*243* @param era the Japanese era, not null244* @param yearOfEra the year-of-era245* @param dayOfYear the day-of-year246* @return the Japanese local date, not null247* @throws DateTimeException if unable to create the date248* @throws ClassCastException if the {@code era} is not a {@code JapaneseEra}249*/250@Override251public JapaneseDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {252return JapaneseDate.ofYearDay((JapaneseEra) era, yearOfEra, dayOfYear);253}254255/**256* Obtains a local date in Japanese calendar system from the257* proleptic-year and day-of-year fields.258* <p>259* The day-of-year in this factory is expressed relative to the start of the proleptic year.260* The Japanese proleptic year and day-of-year are the same as those in the ISO calendar system.261* They are not reset when the era changes.262*263* @param prolepticYear the proleptic-year264* @param dayOfYear the day-of-year265* @return the Japanese local date, not null266* @throws DateTimeException if unable to create the date267*/268@Override269public JapaneseDate dateYearDay(int prolepticYear, int dayOfYear) {270return new JapaneseDate(LocalDate.ofYearDay(prolepticYear, dayOfYear));271}272273/**274* Obtains a local date in the Japanese calendar system from the epoch-day.275*276* @param epochDay the epoch day277* @return the Japanese local date, not null278* @throws DateTimeException if unable to create the date279*/280@Override // override with covariant return type281public JapaneseDate dateEpochDay(long epochDay) {282return new JapaneseDate(LocalDate.ofEpochDay(epochDay));283}284285@Override286public JapaneseDate dateNow() {287return dateNow(Clock.systemDefaultZone());288}289290@Override291public JapaneseDate dateNow(ZoneId zone) {292return dateNow(Clock.system(zone));293}294295@Override296public JapaneseDate dateNow(Clock clock) {297return date(LocalDate.now(clock));298}299300@Override301public JapaneseDate date(TemporalAccessor temporal) {302if (temporal instanceof JapaneseDate) {303return (JapaneseDate) temporal;304}305return new JapaneseDate(LocalDate.from(temporal));306}307308@Override309@SuppressWarnings("unchecked")310public ChronoLocalDateTime<JapaneseDate> localDateTime(TemporalAccessor temporal) {311return (ChronoLocalDateTime<JapaneseDate>)super.localDateTime(temporal);312}313314@Override315@SuppressWarnings("unchecked")316public ChronoZonedDateTime<JapaneseDate> zonedDateTime(TemporalAccessor temporal) {317return (ChronoZonedDateTime<JapaneseDate>)super.zonedDateTime(temporal);318}319320@Override321@SuppressWarnings("unchecked")322public ChronoZonedDateTime<JapaneseDate> zonedDateTime(Instant instant, ZoneId zone) {323return (ChronoZonedDateTime<JapaneseDate>)super.zonedDateTime(instant, zone);324}325326//-----------------------------------------------------------------------327/**328* Checks if the specified year is a leap year.329* <p>330* Japanese calendar leap years occur exactly in line with ISO leap years.331* This method does not validate the year passed in, and only has a332* well-defined result for years in the supported range.333*334* @param prolepticYear the proleptic-year to check, not validated for range335* @return true if the year is a leap year336*/337@Override338public boolean isLeapYear(long prolepticYear) {339return IsoChronology.INSTANCE.isLeapYear(prolepticYear);340}341342@Override343public int prolepticYear(Era era, int yearOfEra) {344if (era instanceof JapaneseEra == false) {345throw new ClassCastException("Era must be JapaneseEra");346}347348JapaneseEra jera = (JapaneseEra) era;349int gregorianYear = jera.getPrivateEra().getSinceDate().getYear() + yearOfEra - 1;350if (yearOfEra == 1) {351return gregorianYear;352}353if (gregorianYear >= Year.MIN_VALUE && gregorianYear <= Year.MAX_VALUE) {354LocalGregorianCalendar.Date jdate = JCAL.newCalendarDate(null);355jdate.setEra(jera.getPrivateEra()).setDate(yearOfEra, 1, 1);356if (JapaneseChronology.JCAL.validate(jdate)) {357return gregorianYear;358}359}360throw new DateTimeException("Invalid yearOfEra value");361}362363/**364* Returns the calendar system era object from the given numeric value.365*366* The numeric values supported by this method are the same as the367* numeric values supported by {@link JapaneseEra#of(int)}.368*369* @param eraValue the era value370* @return the Japanese {@code Era} for the given numeric era value371* @throws DateTimeException if {@code eraValue} is invalid372*/373@Override374public JapaneseEra eraOf(int eraValue) {375return JapaneseEra.of(eraValue);376}377378@Override379public List<Era> eras() {380return List.of(JapaneseEra.values());381}382383JapaneseEra getCurrentEra() {384// Assume that the last JapaneseEra is the current one.385JapaneseEra[] eras = JapaneseEra.values();386return eras[eras.length - 1];387}388389//-----------------------------------------------------------------------390@Override391public ValueRange range(ChronoField field) {392switch (field) {393case ALIGNED_DAY_OF_WEEK_IN_MONTH:394case ALIGNED_DAY_OF_WEEK_IN_YEAR:395case ALIGNED_WEEK_OF_MONTH:396case ALIGNED_WEEK_OF_YEAR:397throw new UnsupportedTemporalTypeException("Unsupported field: " + field);398case YEAR_OF_ERA: {399Calendar jcal = Calendar.getInstance(LOCALE);400int startYear = getCurrentEra().getPrivateEra().getSinceDate().getYear();401return ValueRange.of(1, jcal.getGreatestMinimum(Calendar.YEAR),402jcal.getLeastMaximum(Calendar.YEAR) + 1, // +1 due to the different definitions403Year.MAX_VALUE - startYear);404}405case DAY_OF_YEAR: {406Calendar jcal = Calendar.getInstance(LOCALE);407int fieldIndex = Calendar.DAY_OF_YEAR;408return ValueRange.of(jcal.getMinimum(fieldIndex), jcal.getGreatestMinimum(fieldIndex),409jcal.getLeastMaximum(fieldIndex), jcal.getMaximum(fieldIndex));410}411case YEAR:412return ValueRange.of(JapaneseDate.MEIJI_6_ISODATE.getYear(), Year.MAX_VALUE);413case ERA:414return ValueRange.of(JapaneseEra.MEIJI.getValue(), getCurrentEra().getValue());415default:416return field.range();417}418}419420//-----------------------------------------------------------------------421@Override // override for return type422public JapaneseDate resolveDate(Map <TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {423return (JapaneseDate) super.resolveDate(fieldValues, resolverStyle);424}425426@Override // override for special Japanese behavior427ChronoLocalDate resolveYearOfEra(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {428// validate era and year-of-era429Long eraLong = fieldValues.get(ERA);430JapaneseEra era = null;431if (eraLong != null) {432era = eraOf(range(ERA).checkValidIntValue(eraLong, ERA)); // always validated433}434Long yoeLong = fieldValues.get(YEAR_OF_ERA);435int yoe = 0;436if (yoeLong != null) {437yoe = range(YEAR_OF_ERA).checkValidIntValue(yoeLong, YEAR_OF_ERA); // always validated438}439// if only year-of-era and no year then invent era unless strict440if (era == null && yoeLong != null && fieldValues.containsKey(YEAR) == false && resolverStyle != ResolverStyle.STRICT) {441era = JapaneseEra.values()[JapaneseEra.values().length - 1];442}443// if both present, then try to create date444if (yoeLong != null && era != null) {445if (fieldValues.containsKey(MONTH_OF_YEAR)) {446if (fieldValues.containsKey(DAY_OF_MONTH)) {447return resolveYMD(era, yoe, fieldValues, resolverStyle);448}449}450if (fieldValues.containsKey(DAY_OF_YEAR)) {451return resolveYD(era, yoe, fieldValues, resolverStyle);452}453}454return null;455}456457private int prolepticYearLenient(JapaneseEra era, int yearOfEra) {458return era.getPrivateEra().getSinceDate().getYear() + yearOfEra - 1;459}460461private ChronoLocalDate resolveYMD(JapaneseEra era, int yoe, Map<TemporalField,Long> fieldValues, ResolverStyle resolverStyle) {462fieldValues.remove(ERA);463fieldValues.remove(YEAR_OF_ERA);464if (resolverStyle == ResolverStyle.LENIENT) {465int y = prolepticYearLenient(era, yoe);466long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);467long days = Math.subtractExact(fieldValues.remove(DAY_OF_MONTH), 1);468return date(y, 1, 1).plus(months, MONTHS).plus(days, DAYS);469}470int moy = range(MONTH_OF_YEAR).checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR), MONTH_OF_YEAR);471int dom = range(DAY_OF_MONTH).checkValidIntValue(fieldValues.remove(DAY_OF_MONTH), DAY_OF_MONTH);472if (resolverStyle == ResolverStyle.SMART) { // previous valid473if (yoe < 1) {474throw new DateTimeException("Invalid YearOfEra: " + yoe);475}476int y = prolepticYearLenient(era, yoe);477JapaneseDate result;478try {479result = date(y, moy, dom);480} catch (DateTimeException ex) {481result = date(y, moy, 1).with(TemporalAdjusters.lastDayOfMonth());482}483// handle the era being changed484// only allow if the new date is in the same Jan-Dec as the era change485// determine by ensuring either original yoe or result yoe is 1486if (result.getEra() != era && result.get(YEAR_OF_ERA) > 1 && yoe > 1) {487throw new DateTimeException("Invalid YearOfEra for Era: " + era + " " + yoe);488}489return result;490}491return date(era, yoe, moy, dom);492}493494private ChronoLocalDate resolveYD(JapaneseEra era, int yoe, Map <TemporalField,Long> fieldValues, ResolverStyle resolverStyle) {495fieldValues.remove(ERA);496fieldValues.remove(YEAR_OF_ERA);497if (resolverStyle == ResolverStyle.LENIENT) {498int y = prolepticYearLenient(era, yoe);499long days = Math.subtractExact(fieldValues.remove(DAY_OF_YEAR), 1);500return dateYearDay(y, 1).plus(days, DAYS);501}502int doy = range(DAY_OF_YEAR).checkValidIntValue(fieldValues.remove(DAY_OF_YEAR), DAY_OF_YEAR);503return dateYearDay(era, yoe, doy); // smart is same as strict504}505506//-----------------------------------------------------------------------507/**508* Writes the Chronology using a509* <a href="{@docRoot}/serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.510* @serialData511* <pre>512* out.writeByte(1); // identifies a Chronology513* out.writeUTF(getId());514* </pre>515*516* @return the instance of {@code Ser}, not null517*/518@Override519@java.io.Serial520Object writeReplace() {521return super.writeReplace();522}523524/**525* Defend against malicious streams.526*527* @param s the stream to read528* @throws InvalidObjectException always529*/530@java.io.Serial531private void readObject(ObjectInputStream s) throws InvalidObjectException {532throw new InvalidObjectException("Deserialization via serialization delegate");533}534}535536537