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.io.InvalidObjectException;
  69 import java.io.Serializable;
  70 import java.time.DateTimeException;
  71 import java.time.LocalDate;
  72 import java.time.format.DateTimeBuilder;
  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  *
  81  * <h3>Specification for implementors</h3>
  82  * This is an immutable and thread-safe class.
  83  *
  84  * @since 1.8
  85  */
  86 public final class JulianFields {
  87 
  88     /**
  89      * The offset from Julian to EPOCH DAY.
  90      */
  91     private static final long JULIAN_DAY_OFFSET = 2440588L;
  92 
  93     /**
  94      * Julian Day field.
  95      * <p>
  96      * This is an integer-based version of the Julian Day Number.
  97      * Julian Day is a well-known system that represents the count of whole days since day 0,
  98      * which is defined to be January 1, 4713 BCE in the Julian calendar, and -4713-11-24 Gregorian.
  99      * The field  has "JulianDay" as 'name', and 'DAYS' as 'baseUnit'.
 100      * The field always refers to the local date-time, ignoring the offset or zone.
 101      * <p>
 102      * For date-times, 'JULIAN_DAY.doGet()' assumes the same value from
 103      * midnight until just before the next midnight.
 104      * When 'JULIAN_DAY.doWith()' is applied to a date-time, the time of day portion remains unaltered.
 105      * 'JULIAN_DAY.doWith()' and 'JULIAN_DAY.doGet()' only apply to {@code Temporal} objects that
 106      * can be converted into {@link ChronoField#EPOCH_DAY}.
 107      * A {@link DateTimeException} is thrown for any other type of object.
 108      * <p>
 109      * <h3>Astronomical and Scientific Notes</h3>
 110      * The standard astronomical definition uses a fraction to indicate the time-of-day,
 111      * thus 3.25 would represent the time 18:00, since days start at midday.
 112      * This implementation uses an integer and days starting at midnight.
 113      * The integer value for the Julian Day Number is the astronomical Julian Day value at midday
 114      * of the date in question.
 115      * This amounts to the astronomical Julian Day, rounded to an integer {@code JDN = floor(JD + 0.5)}.
 116      * <p>
 117      * <pre>
 118      *  | ISO date          |  Julian Day Number | Astronomical Julian Day |
 119      *  | 1970-01-01T00:00  |         2,440,588  |         2,440,587.5     |
 120      *  | 1970-01-01T06:00  |         2,440,588  |         2,440,587.75    |
 121      *  | 1970-01-01T12:00  |         2,440,588  |         2,440,588.0     |
 122      *  | 1970-01-01T18:00  |         2,440,588  |         2,440,588.25    |
 123      *  | 1970-01-02T00:00  |         2,440,589  |         2,440,588.5     |
 124      *  | 1970-01-02T06:00  |         2,440,589  |         2,440,588.75    |
 125      *  | 1970-01-02T12:00  |         2,440,589  |         2,440,589.0     |
 126      * </pre>
 127      * <p>
 128      * Julian Days are sometimes taken to imply Universal Time or UTC, but this
 129      * implementation always uses the Julian Day number for the local date,
 130      * regardless of the offset or time-zone.
 131      */
 132     public static final TemporalField JULIAN_DAY = new Field("JulianDay", DAYS, FOREVER, JULIAN_DAY_OFFSET);
 133 
 134     /**
 135      * Modified Julian Day field.
 136      * <p>
 137      * This is an integer-based version of the Modified Julian Day Number.
 138      * Modified Julian Day (MJD) is a well-known system that counts days continuously.
 139      * It is defined relative to astronomical Julian Day as  {@code MJD = JD - 2400000.5}.
 140      * Each Modified Julian Day runs from midnight to midnight.
 141      * The field always refers to the local date-time, ignoring the offset or zone.
 142      * <p>
 143      * For date-times, 'MODIFIED_JULIAN_DAY.doGet()' assumes the same value from
 144      * midnight until just before the next midnight.
 145      * When 'MODIFIED_JULIAN_DAY.doWith()' is applied to a date-time, the time of day portion remains unaltered.
 146      * 'MODIFIED_JULIAN_DAY.doWith()' and 'MODIFIED_JULIAN_DAY.doGet()' only apply to {@code Temporal} objects
 147      * that can be converted into {@link ChronoField#EPOCH_DAY}.
 148      * A {@link DateTimeException} is thrown for any other type of object.
 149      * <p>
 150      * This implementation is an integer version of MJD with the decimal part rounded to floor.
 151      * <p>
 152      * <h3>Astronomical and Scientific Notes</h3>
 153      * <pre>
 154      *  | ISO date          | Modified Julian Day |      Decimal MJD |
 155      *  | 1970-01-01T00:00  |             40,587  |       40,587.0   |
 156      *  | 1970-01-01T06:00  |             40,587  |       40,587.25  |
 157      *  | 1970-01-01T12:00  |             40,587  |       40,587.5   |
 158      *  | 1970-01-01T18:00  |             40,587  |       40,587.75  |
 159      *  | 1970-01-02T00:00  |             40,588  |       40,588.0   |
 160      *  | 1970-01-02T06:00  |             40,588  |       40,588.25  |
 161      *  | 1970-01-02T12:00  |             40,588  |       40,588.5   |
 162      * </pre>
 163      * <p>
 164      * Modified Julian Days are sometimes taken to imply Universal Time or UTC, but this
 165      * implementation always uses the Modified Julian Day for the local date,
 166      * regardless of the offset or time-zone.
 167      */
 168     public static final TemporalField MODIFIED_JULIAN_DAY = new Field("ModifiedJulianDay", DAYS, FOREVER, 40587L);
 169 
 170     /**
 171      * Rata Die field.
 172      * <p>
 173      * Rata Die counts whole days continuously starting day 1 at midnight at the beginning of 0001-01-01 (ISO).
 174      * The field always refers to the local date-time, ignoring the offset or zone.
 175      * <p>
 176      * For date-times, 'RATA_DIE.doGet()' assumes the same value from
 177      * midnight until just before the next midnight.
 178      * When 'RATA_DIE.doWith()' is applied to a date-time, the time of day portion remains unaltered.
 179      * 'MODIFIED_JULIAN_DAY.doWith()' and 'RATA_DIE.doGet()' only apply to {@code Temporal} objects
 180      * that can be converted into {@link ChronoField#EPOCH_DAY}.
 181      * A {@link DateTimeException} is thrown for any other type of object.
 182      */
 183     public static final TemporalField RATA_DIE = new Field("RataDie", DAYS, FOREVER, 719163L);
 184 
 185     /**
 186      * Restricted constructor.
 187      */
 188     private JulianFields() {
 189         throw new AssertionError("Not instantiable");
 190     }
 191 
 192     /**
 193      * implementation of JulianFields.  Each instance is a singleton.
 194      */
 195     private static class Field implements TemporalField, Serializable {
 196 
 197         private static final long serialVersionUID = -7501623920830201812L;
 198 
 199         private final String name;
 200         private final transient TemporalUnit baseUnit;
 201         private final transient TemporalUnit rangeUnit;
 202         private final transient ValueRange range;
 203         private final transient long offset;
 204 
 205         private Field(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit, long offset) {
 206             this.name = name;
 207             this.baseUnit = baseUnit;
 208             this.rangeUnit = rangeUnit;
 209             this.range = ValueRange.of(-365243219162L + offset, 365241780471L + offset);
 210             this.offset = offset;
 211         }
 212 
 213 
 214         /**
 215          * Resolve the object from the stream to the appropriate singleton.
 216          * @return one of the singleton objects {@link #JULIAN_DAY},
 217          *     {@link #MODIFIED_JULIAN_DAY}, or {@link #RATA_DIE}.
 218          * @throws InvalidObjectException if the object in the stream is not one of the singletons.
 219          */
 220         private Object readResolve() throws InvalidObjectException {
 221             if (JULIAN_DAY.getName().equals(name)) {
 222                 return JULIAN_DAY;
 223             } else if (MODIFIED_JULIAN_DAY.getName().equals(name)) {
 224                 return MODIFIED_JULIAN_DAY;
 225             } else if (RATA_DIE.getName().equals(name)) {
 226                 return RATA_DIE;
 227             } else {
 228                 throw new InvalidObjectException("Not one of the singletons");
 229             }
 230         }
 231 
 232         //-----------------------------------------------------------------------
 233         @Override
 234         public String getName() {
 235             return name;
 236         }
 237 
 238         @Override
 239         public TemporalUnit getBaseUnit() {
 240             return baseUnit;
 241         }
 242 
 243         @Override
 244         public TemporalUnit getRangeUnit() {
 245             return rangeUnit;
 246         }
 247 
 248         @Override
 249         public ValueRange range() {
 250             return range;
 251         }
 252 
 253         //-----------------------------------------------------------------------
 254         @Override
 255         public boolean doIsSupported(TemporalAccessor temporal) {
 256             return temporal.isSupported(EPOCH_DAY);
 257         }
 258 
 259         @Override
 260         public ValueRange doRange(TemporalAccessor temporal) {
 261             if (doIsSupported(temporal) == false) {
 262                 throw new DateTimeException("Unsupported field: " + this);
 263             }
 264             return range();
 265         }
 266 
 267         @Override
 268         public long doGet(TemporalAccessor temporal) {
 269             return temporal.getLong(EPOCH_DAY) + offset;
 270         }
 271 
 272         @Override
 273         public <R extends Temporal> R doWith(R temporal, long newValue) {
 274             if (range().isValidValue(newValue) == false) {
 275                 throw new DateTimeException("Invalid value: " + name + " " + newValue);
 276             }
 277             return (R) temporal.with(EPOCH_DAY, Math.subtractExact(newValue, offset));
 278         }
 279 
 280         //-----------------------------------------------------------------------
 281         @Override
 282         public boolean resolve(DateTimeBuilder builder, long value) {
 283             boolean changed = false;
 284             changed = resolve0(JULIAN_DAY, builder, changed);
 285             changed = resolve0(MODIFIED_JULIAN_DAY, builder, changed);
 286             changed = resolve0(RATA_DIE, builder, changed);
 287             return changed;
 288         }
 289 
 290         private boolean resolve0(TemporalField field, DateTimeBuilder builder, boolean changed) {
 291             if (builder.containsFieldValue(field)) {
 292                 builder.addCalendrical(LocalDate.ofEpochDay(Math.subtractExact(builder.getFieldValue(JULIAN_DAY), JULIAN_DAY_OFFSET)));
 293                 builder.removeFieldValue(JULIAN_DAY);
 294                 changed = true;
 295             }
 296             return changed;
 297         }
 298 
 299         //-----------------------------------------------------------------------
 300         @Override
 301         public String toString() {
 302             return getName();
 303         }
 304     }
 305 }