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  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file:
  31  *
  32  * Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
  33  *
  34  * All rights reserved.
  35  *
  36  * Redistribution and use in source and binary forms, with or without
  37  * modification, are permitted provided that the following conditions are met:
  38  *
  39  *  * Redistributions of source code must retain the above copyright notice,
  40  *    this list of conditions and the following disclaimer.
  41  *
  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time.temporal;
  63 
  64 import static java.time.temporal.ChronoField.EPOCH_DAY;
  65 import static java.time.temporal.ChronoUnit.DAYS;
  66 import static java.time.temporal.ChronoUnit.FOREVER;
  67 
  68 import java.time.DateTimeException;
  69 import java.time.chrono.ChronoLocalDate;
  70 import java.time.chrono.Chronology;
  71 import java.time.format.ResolverStyle;
  72 import java.util.Map;
  73 
  74 /**
  75  * A set of date fields that provide access to Julian Days.
  76  * <p>
  77  * The Julian Day is a standard way of expressing date and time commonly used in the scientific community.
  78  * It is expressed as a decimal number of whole days where days start at midday.
  79  * This class represents variations on Julian Days that count whole days from midnight.
  80  * <p>
  81  * The fields are implemented relative to {@link ChronoField#EPOCH_DAY EPOCH_DAY}.
  82  * The fields are supported, and can be queried and set if {@code EPOCH_DAY} is available.
  83  * The fields work with all chronologies.
  84  *
  85  * @implSpec
  86  * This is an immutable and thread-safe class.
  87  *
  88  * @since 1.8
  89  */
  90 public final class JulianFields {
  91 
  92     /**
  93      * The offset from Julian to EPOCH DAY.
  94      */
  95     private static final long JULIAN_DAY_OFFSET = 2440588L;
  96 
  97     /**
  98      * Julian Day field.
  99      * <p>
 100      * This is an integer-based version of the Julian Day Number.
 101      * Julian Day is a well-known system that represents the count of whole days since day 0,
 102      * which is defined to be January 1, 4713 BCE in the Julian calendar, and -4713-11-24 Gregorian.
 103      * The field  has "JulianDay" as 'name', and 'DAYS' as 'baseUnit'.
 104      * The field always refers to the local date-time, ignoring the offset or zone.
 105      * <p>
 106      * For date-times, 'JULIAN_DAY.getFrom()' assumes the same value from
 107      * midnight until just before the next midnight.
 108      * When 'JULIAN_DAY.adjustInto()' is applied to a date-time, the time of day portion remains unaltered.
 109      * 'JULIAN_DAY.adjustInto()' and 'JULIAN_DAY.getFrom()' only apply to {@code Temporal} objects that
 110      * can be converted into {@link ChronoField#EPOCH_DAY}.
 111      * An {@link UnsupportedTemporalTypeException} is thrown for any other type of object.
 112      * <p>
 113      * In the resolving phase of parsing, a date can be created from a Julian Day field.
 114      * In {@linkplain ResolverStyle#STRICT strict mode} and {@linkplain ResolverStyle#SMART smart mode}
 115      * the Julian Day value is validated against the range of valid values.
 116      * In {@linkplain ResolverStyle#LENIENT lenient mode} no validation occurs.
 117      *
 118      * <h3>Astronomical and Scientific Notes</h3>
 119      * The standard astronomical definition uses a fraction to indicate the time-of-day,
 120      * thus 3.25 would represent the time 18:00, since days start at midday.
 121      * This implementation uses an integer and days starting at midnight.
 122      * The integer value for the Julian Day Number is the astronomical Julian Day value at midday
 123      * of the date in question.
 124      * This amounts to the astronomical Julian Day, rounded to an integer {@code JDN = floor(JD + 0.5)}.
 125      *
 126      * <pre>
 127      *  | ISO date          |  Julian Day Number | Astronomical Julian Day |
 128      *  | 1970-01-01T00:00  |         2,440,588  |         2,440,587.5     |
 129      *  | 1970-01-01T06:00  |         2,440,588  |         2,440,587.75    |
 130      *  | 1970-01-01T12:00  |         2,440,588  |         2,440,588.0     |
 131      *  | 1970-01-01T18:00  |         2,440,588  |         2,440,588.25    |
 132      *  | 1970-01-02T00:00  |         2,440,589  |         2,440,588.5     |
 133      *  | 1970-01-02T06:00  |         2,440,589  |         2,440,588.75    |
 134      *  | 1970-01-02T12:00  |         2,440,589  |         2,440,589.0     |
 135      * </pre>
 136      * <p>
 137      * Julian Days are sometimes taken to imply Universal Time or UTC, but this
 138      * implementation always uses the Julian Day number for the local date,
 139      * regardless of the offset or time-zone.
 140      */
 141     public static final TemporalField JULIAN_DAY = Field.JULIAN_DAY;
 142 
 143     /**
 144      * Modified Julian Day field.
 145      * <p>
 146      * This is an integer-based version of the Modified Julian Day Number.
 147      * Modified Julian Day (MJD) is a well-known system that counts days continuously.
 148      * It is defined relative to astronomical Julian Day as  {@code MJD = JD - 2400000.5}.
 149      * Each Modified Julian Day runs from midnight to midnight.
 150      * The field always refers to the local date-time, ignoring the offset or zone.
 151      * <p>
 152      * For date-times, 'MODIFIED_JULIAN_DAY.getFrom()' assumes the same value from
 153      * midnight until just before the next midnight.
 154      * When 'MODIFIED_JULIAN_DAY.adjustInto()' is applied to a date-time, the time of day portion remains unaltered.
 155      * 'MODIFIED_JULIAN_DAY.adjustInto()' and 'MODIFIED_JULIAN_DAY.getFrom()' only apply to {@code Temporal} objects
 156      * that can be converted into {@link ChronoField#EPOCH_DAY}.
 157      * An {@link UnsupportedTemporalTypeException} is thrown for any other type of object.
 158      * <p>
 159      * This implementation is an integer version of MJD with the decimal part rounded to floor.
 160      * <p>
 161      * In the resolving phase of parsing, a date can be created from a Modified Julian Day field.
 162      * In {@linkplain ResolverStyle#STRICT strict mode} and {@linkplain ResolverStyle#SMART smart mode}
 163      * the Modified Julian Day value is validated against the range of valid values.
 164      * In {@linkplain ResolverStyle#LENIENT lenient mode} no validation occurs.
 165      *
 166      * <h3>Astronomical and Scientific Notes</h3>
 167      * <pre>
 168      *  | ISO date          | Modified Julian Day |      Decimal MJD |
 169      *  | 1970-01-01T00:00  |             40,587  |       40,587.0   |
 170      *  | 1970-01-01T06:00  |             40,587  |       40,587.25  |
 171      *  | 1970-01-01T12:00  |             40,587  |       40,587.5   |
 172      *  | 1970-01-01T18:00  |             40,587  |       40,587.75  |
 173      *  | 1970-01-02T00:00  |             40,588  |       40,588.0   |
 174      *  | 1970-01-02T06:00  |             40,588  |       40,588.25  |
 175      *  | 1970-01-02T12:00  |             40,588  |       40,588.5   |
 176      * </pre>
 177      *
 178      * Modified Julian Days are sometimes taken to imply Universal Time or UTC, but this
 179      * implementation always uses the Modified Julian Day for the local date,
 180      * regardless of the offset or time-zone.
 181      */
 182     public static final TemporalField MODIFIED_JULIAN_DAY = Field.MODIFIED_JULIAN_DAY;
 183 
 184     /**
 185      * Rata Die field.
 186      * <p>
 187      * Rata Die counts whole days continuously starting day 1 at midnight at the beginning of 0001-01-01 (ISO).
 188      * The field always refers to the local date-time, ignoring the offset or zone.
 189      * <p>
 190      * For date-times, 'RATA_DIE.getFrom()' assumes the same value from
 191      * midnight until just before the next midnight.
 192      * When 'RATA_DIE.adjustInto()' is applied to a date-time, the time of day portion remains unaltered.
 193      * 'RATA_DIE.adjustInto()' and 'RATA_DIE.getFrom()' only apply to {@code Temporal} objects
 194      * that can be converted into {@link ChronoField#EPOCH_DAY}.
 195      * An {@link UnsupportedTemporalTypeException} is thrown for any other type of object.
 196      * <p>
 197      * In the resolving phase of parsing, a date can be created from a Rata Die field.
 198      * In {@linkplain ResolverStyle#STRICT strict mode} and {@linkplain ResolverStyle#SMART smart mode}
 199      * the Rata Die value is validated against the range of valid values.
 200      * In {@linkplain ResolverStyle#LENIENT lenient mode} no validation occurs.
 201      */
 202     public static final TemporalField RATA_DIE = Field.RATA_DIE;
 203 
 204     /**
 205      * Restricted constructor.
 206      */
 207     private JulianFields() {
 208         throw new AssertionError("Not instantiable");
 209     }
 210 
 211     /**
 212      * Implementation of JulianFields.  Each instance is a singleton.
 213      */
 214     private static enum Field implements TemporalField {
 215         JULIAN_DAY("JulianDay", DAYS, FOREVER, JULIAN_DAY_OFFSET),
 216         MODIFIED_JULIAN_DAY("ModifiedJulianDay", DAYS, FOREVER, 40587L),
 217         RATA_DIE("RataDie", DAYS, FOREVER, 719163L);
 218 
 219         private static final long serialVersionUID = -7501623920830201812L;
 220 
 221         private final transient String name;
 222         private final transient TemporalUnit baseUnit;
 223         private final transient TemporalUnit rangeUnit;
 224         private final transient ValueRange range;
 225         private final transient long offset;
 226 
 227         private Field(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit, long offset) {
 228             this.name = name;
 229             this.baseUnit = baseUnit;
 230             this.rangeUnit = rangeUnit;
 231             this.range = ValueRange.of(-365243219162L + offset, 365241780471L + offset);
 232             this.offset = offset;
 233         }
 234 
 235         //-----------------------------------------------------------------------
 236         @Override
 237         public TemporalUnit getBaseUnit() {
 238             return baseUnit;
 239         }
 240 
 241         @Override
 242         public TemporalUnit getRangeUnit() {
 243             return rangeUnit;
 244         }
 245 
 246         @Override
 247         public boolean isDateBased() {
 248             return true;
 249         }
 250 
 251         @Override
 252         public boolean isTimeBased() {
 253             return false;
 254         }
 255 
 256         @Override
 257         public ValueRange range() {
 258             return range;
 259         }
 260 
 261         //-----------------------------------------------------------------------
 262         @Override
 263         public boolean isSupportedBy(TemporalAccessor temporal) {
 264             return temporal.isSupported(EPOCH_DAY);
 265         }
 266 
 267         @Override
 268         public ValueRange rangeRefinedBy(TemporalAccessor temporal) {
 269             if (isSupportedBy(temporal) == false) {
 270                 throw new DateTimeException("Unsupported field: " + this);
 271             }
 272             return range();
 273         }
 274 
 275         @Override
 276         public long getFrom(TemporalAccessor temporal) {
 277             return temporal.getLong(EPOCH_DAY) + offset;
 278         }
 279 
 280         @SuppressWarnings("unchecked")
 281         @Override
 282         public <R extends Temporal> R adjustInto(R temporal, long newValue) {
 283             if (range().isValidValue(newValue) == false) {
 284                 throw new DateTimeException("Invalid value: " + name + " " + newValue);
 285             }
 286             return (R) temporal.with(EPOCH_DAY, Math.subtractExact(newValue, offset));
 287         }
 288 
 289         //-----------------------------------------------------------------------
 290         @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);
 300         }
 301 
 302         //-----------------------------------------------------------------------
 303         @Override
 304         public String toString() {
 305             return name;
 306         }
 307     }
 308 }