JulianFields.java 13.9 KB
Newer Older
S
sherman 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
/*
 * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * This file is available under and governed by the GNU General Public
 * License version 2 only, as published by the Free Software Foundation.
 * However, the following notice accompanied the original version of this
 * file:
 *
 * Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither the name of JSR-310 nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package java.time.temporal;

import static java.time.temporal.ChronoField.EPOCH_DAY;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.FOREVER;

import java.time.DateTimeException;
69 70
import java.time.chrono.ChronoLocalDate;
import java.time.chrono.Chronology;
71
import java.time.format.ResolverStyle;
S
sherman 已提交
72
import java.util.Map;
S
sherman 已提交
73 74 75 76 77 78 79

/**
 * A set of date fields that provide access to Julian Days.
 * <p>
 * The Julian Day is a standard way of expressing date and time commonly used in the scientific community.
 * It is expressed as a decimal number of whole days where days start at midday.
 * This class represents variations on Julian Days that count whole days from midnight.
S
sherman 已提交
80 81 82 83
 * <p>
 * The fields are implemented relative to {@link ChronoField#EPOCH_DAY EPOCH_DAY}.
 * The fields are supported, and can be queried and set if {@code EPOCH_DAY} is available.
 * The fields work with all chronologies.
S
sherman 已提交
84
 *
85
 * @implSpec
S
sherman 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
 * This is an immutable and thread-safe class.
 *
 * @since 1.8
 */
public final class JulianFields {

    /**
     * The offset from Julian to EPOCH DAY.
     */
    private static final long JULIAN_DAY_OFFSET = 2440588L;

    /**
     * Julian Day field.
     * <p>
     * This is an integer-based version of the Julian Day Number.
     * Julian Day is a well-known system that represents the count of whole days since day 0,
     * which is defined to be January 1, 4713 BCE in the Julian calendar, and -4713-11-24 Gregorian.
     * The field  has "JulianDay" as 'name', and 'DAYS' as 'baseUnit'.
     * The field always refers to the local date-time, ignoring the offset or zone.
     * <p>
S
sherman 已提交
106
     * For date-times, 'JULIAN_DAY.getFrom()' assumes the same value from
S
sherman 已提交
107
     * midnight until just before the next midnight.
S
sherman 已提交
108 109
     * When 'JULIAN_DAY.adjustInto()' is applied to a date-time, the time of day portion remains unaltered.
     * 'JULIAN_DAY.adjustInto()' and 'JULIAN_DAY.getFrom()' only apply to {@code Temporal} objects that
S
sherman 已提交
110
     * can be converted into {@link ChronoField#EPOCH_DAY}.
111 112 113 114 115 116
     * An {@link UnsupportedTemporalTypeException} is thrown for any other type of object.
     * <p>
     * In the resolving phase of parsing, a date can be created from a Julian Day field.
     * In {@linkplain ResolverStyle#STRICT strict mode} and {@linkplain ResolverStyle#SMART smart mode}
     * the Julian Day value is validated against the range of valid values.
     * In {@linkplain ResolverStyle#LENIENT lenient mode} no validation occurs.
R
rriggs 已提交
117
     *
S
sherman 已提交
118 119 120 121 122 123 124
     * <h3>Astronomical and Scientific Notes</h3>
     * The standard astronomical definition uses a fraction to indicate the time-of-day,
     * thus 3.25 would represent the time 18:00, since days start at midday.
     * This implementation uses an integer and days starting at midnight.
     * The integer value for the Julian Day Number is the astronomical Julian Day value at midday
     * of the date in question.
     * This amounts to the astronomical Julian Day, rounded to an integer {@code JDN = floor(JD + 0.5)}.
R
rriggs 已提交
125
     *
S
sherman 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
     * <pre>
     *  | ISO date          |  Julian Day Number | Astronomical Julian Day |
     *  | 1970-01-01T00:00  |         2,440,588  |         2,440,587.5     |
     *  | 1970-01-01T06:00  |         2,440,588  |         2,440,587.75    |
     *  | 1970-01-01T12:00  |         2,440,588  |         2,440,588.0     |
     *  | 1970-01-01T18:00  |         2,440,588  |         2,440,588.25    |
     *  | 1970-01-02T00:00  |         2,440,589  |         2,440,588.5     |
     *  | 1970-01-02T06:00  |         2,440,589  |         2,440,588.75    |
     *  | 1970-01-02T12:00  |         2,440,589  |         2,440,589.0     |
     * </pre>
     * <p>
     * Julian Days are sometimes taken to imply Universal Time or UTC, but this
     * implementation always uses the Julian Day number for the local date,
     * regardless of the offset or time-zone.
     */
S
sherman 已提交
141
    public static final TemporalField JULIAN_DAY = Field.JULIAN_DAY;
S
sherman 已提交
142 143 144 145 146 147 148 149 150 151

    /**
     * Modified Julian Day field.
     * <p>
     * This is an integer-based version of the Modified Julian Day Number.
     * Modified Julian Day (MJD) is a well-known system that counts days continuously.
     * It is defined relative to astronomical Julian Day as  {@code MJD = JD - 2400000.5}.
     * Each Modified Julian Day runs from midnight to midnight.
     * The field always refers to the local date-time, ignoring the offset or zone.
     * <p>
S
sherman 已提交
152
     * For date-times, 'MODIFIED_JULIAN_DAY.getFrom()' assumes the same value from
S
sherman 已提交
153
     * midnight until just before the next midnight.
S
sherman 已提交
154 155
     * When 'MODIFIED_JULIAN_DAY.adjustInto()' is applied to a date-time, the time of day portion remains unaltered.
     * 'MODIFIED_JULIAN_DAY.adjustInto()' and 'MODIFIED_JULIAN_DAY.getFrom()' only apply to {@code Temporal} objects
S
sherman 已提交
156
     * that can be converted into {@link ChronoField#EPOCH_DAY}.
157
     * An {@link UnsupportedTemporalTypeException} is thrown for any other type of object.
S
sherman 已提交
158 159 160
     * <p>
     * This implementation is an integer version of MJD with the decimal part rounded to floor.
     * <p>
161 162 163 164
     * In the resolving phase of parsing, a date can be created from a Modified Julian Day field.
     * In {@linkplain ResolverStyle#STRICT strict mode} and {@linkplain ResolverStyle#SMART smart mode}
     * the Modified Julian Day value is validated against the range of valid values.
     * In {@linkplain ResolverStyle#LENIENT lenient mode} no validation occurs.
R
rriggs 已提交
165
     *
S
sherman 已提交
166 167 168 169 170 171 172 173 174 175 176
     * <h3>Astronomical and Scientific Notes</h3>
     * <pre>
     *  | ISO date          | Modified Julian Day |      Decimal MJD |
     *  | 1970-01-01T00:00  |             40,587  |       40,587.0   |
     *  | 1970-01-01T06:00  |             40,587  |       40,587.25  |
     *  | 1970-01-01T12:00  |             40,587  |       40,587.5   |
     *  | 1970-01-01T18:00  |             40,587  |       40,587.75  |
     *  | 1970-01-02T00:00  |             40,588  |       40,588.0   |
     *  | 1970-01-02T06:00  |             40,588  |       40,588.25  |
     *  | 1970-01-02T12:00  |             40,588  |       40,588.5   |
     * </pre>
R
rriggs 已提交
177
     *
S
sherman 已提交
178 179 180 181
     * Modified Julian Days are sometimes taken to imply Universal Time or UTC, but this
     * implementation always uses the Modified Julian Day for the local date,
     * regardless of the offset or time-zone.
     */
S
sherman 已提交
182
    public static final TemporalField MODIFIED_JULIAN_DAY = Field.MODIFIED_JULIAN_DAY;
S
sherman 已提交
183 184 185 186 187 188 189

    /**
     * Rata Die field.
     * <p>
     * Rata Die counts whole days continuously starting day 1 at midnight at the beginning of 0001-01-01 (ISO).
     * The field always refers to the local date-time, ignoring the offset or zone.
     * <p>
S
sherman 已提交
190
     * For date-times, 'RATA_DIE.getFrom()' assumes the same value from
S
sherman 已提交
191
     * midnight until just before the next midnight.
S
sherman 已提交
192 193
     * When 'RATA_DIE.adjustInto()' is applied to a date-time, the time of day portion remains unaltered.
     * 'RATA_DIE.adjustInto()' and 'RATA_DIE.getFrom()' only apply to {@code Temporal} objects
S
sherman 已提交
194
     * that can be converted into {@link ChronoField#EPOCH_DAY}.
195 196 197 198 199 200
     * An {@link UnsupportedTemporalTypeException} is thrown for any other type of object.
     * <p>
     * In the resolving phase of parsing, a date can be created from a Rata Die field.
     * In {@linkplain ResolverStyle#STRICT strict mode} and {@linkplain ResolverStyle#SMART smart mode}
     * the Rata Die value is validated against the range of valid values.
     * In {@linkplain ResolverStyle#LENIENT lenient mode} no validation occurs.
S
sherman 已提交
201
     */
S
sherman 已提交
202
    public static final TemporalField RATA_DIE = Field.RATA_DIE;
S
sherman 已提交
203 204 205 206 207 208 209 210 211

    /**
     * Restricted constructor.
     */
    private JulianFields() {
        throw new AssertionError("Not instantiable");
    }

    /**
S
sherman 已提交
212
     * Implementation of JulianFields.  Each instance is a singleton.
S
sherman 已提交
213
     */
S
sherman 已提交
214 215 216 217
    private static enum Field implements TemporalField {
        JULIAN_DAY("JulianDay", DAYS, FOREVER, JULIAN_DAY_OFFSET),
        MODIFIED_JULIAN_DAY("ModifiedJulianDay", DAYS, FOREVER, 40587L),
        RATA_DIE("RataDie", DAYS, FOREVER, 719163L);
S
sherman 已提交
218 219 220

        private static final long serialVersionUID = -7501623920830201812L;

S
sherman 已提交
221
        private final transient String name;
S
sherman 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
        private final transient TemporalUnit baseUnit;
        private final transient TemporalUnit rangeUnit;
        private final transient ValueRange range;
        private final transient long offset;

        private Field(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit, long offset) {
            this.name = name;
            this.baseUnit = baseUnit;
            this.rangeUnit = rangeUnit;
            this.range = ValueRange.of(-365243219162L + offset, 365241780471L + offset);
            this.offset = offset;
        }

        //-----------------------------------------------------------------------
        @Override
        public TemporalUnit getBaseUnit() {
            return baseUnit;
        }

        @Override
        public TemporalUnit getRangeUnit() {
            return rangeUnit;
        }

246 247 248 249 250
        @Override
        public boolean isDateBased() {
            return true;
        }

251 252 253 254 255
        @Override
        public boolean isTimeBased() {
            return false;
        }

S
sherman 已提交
256 257 258 259 260 261 262
        @Override
        public ValueRange range() {
            return range;
        }

        //-----------------------------------------------------------------------
        @Override
S
sherman 已提交
263
        public boolean isSupportedBy(TemporalAccessor temporal) {
S
sherman 已提交
264 265 266 267
            return temporal.isSupported(EPOCH_DAY);
        }

        @Override
S
sherman 已提交
268 269
        public ValueRange rangeRefinedBy(TemporalAccessor temporal) {
            if (isSupportedBy(temporal) == false) {
S
sherman 已提交
270 271 272 273 274 275
                throw new DateTimeException("Unsupported field: " + this);
            }
            return range();
        }

        @Override
S
sherman 已提交
276
        public long getFrom(TemporalAccessor temporal) {
S
sherman 已提交
277 278 279
            return temporal.getLong(EPOCH_DAY) + offset;
        }

S
sherman 已提交
280
        @SuppressWarnings("unchecked")
S
sherman 已提交
281
        @Override
S
sherman 已提交
282
        public <R extends Temporal> R adjustInto(R temporal, long newValue) {
S
sherman 已提交
283 284 285 286 287 288 289 290
            if (range().isValidValue(newValue) == false) {
                throw new DateTimeException("Invalid value: " + name + " " + newValue);
            }
            return (R) temporal.with(EPOCH_DAY, Math.subtractExact(newValue, offset));
        }

        //-----------------------------------------------------------------------
        @Override
291
        public ChronoLocalDate resolve(
292
                Map<TemporalField, Long> fieldValues, TemporalAccessor partialTemporal, ResolverStyle resolverStyle) {
293
            long value = fieldValues.remove(this);
294
            Chronology chrono = Chronology.from(partialTemporal);
295
            if (resolverStyle == ResolverStyle.LENIENT) {
296
                return chrono.dateEpochDay(Math.subtractExact(value, offset));
297
            }
298
            range().checkValidValue(value, this);
299
            return chrono.dateEpochDay(value - offset);
S
sherman 已提交
300 301 302 303 304
        }

        //-----------------------------------------------------------------------
        @Override
        public String toString() {
S
sherman 已提交
305
            return name;
S
sherman 已提交
306 307 308
        }
    }
}