AbsoluteDate.java

  1. /* Copyright 2002-2020 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.time;

  18. import java.io.Serializable;
  19. import java.util.Date;
  20. import java.util.TimeZone;

  21. import org.hipparchus.util.FastMath;
  22. import org.orekit.annotation.DefaultDataContext;
  23. import org.orekit.data.DataContext;
  24. import org.orekit.errors.OrekitException;
  25. import org.orekit.errors.OrekitIllegalArgumentException;
  26. import org.orekit.errors.OrekitMessages;
  27. import org.orekit.utils.Constants;


  28. /** This class represents a specific instant in time.

  29.  * <p>Instances of this class are considered to be absolute in the sense
  30.  * that each one represent the occurrence of some event and can be compared
  31.  * to other instances or located in <em>any</em> {@link TimeScale time scale}. In
  32.  * other words the different locations of an event with respect to two different
  33.  * time scales (say {@link TAIScale TAI} and {@link UTCScale UTC} for example) are
  34.  * simply different perspective related to a single object. Only one
  35.  * <code>AbsoluteDate</code> instance is needed, both representations being available
  36.  * from this single instance by specifying the time scales as parameter when calling
  37.  * the ad-hoc methods.</p>
  38.  *
  39.  * <p>Since an instance is not bound to a specific time-scale, all methods related
  40.  * to the location of the date within some time scale require to provide the time
  41.  * scale as an argument. It is therefore possible to define a date in one time scale
  42.  * and to use it in another one. An example of such use is to read a date from a file
  43.  * in UTC and write it in another file in TAI. This can be done as follows:</p>
  44.  * <pre>
  45.  *   DateTimeComponents utcComponents = readNextDate();
  46.  *   AbsoluteDate date = new AbsoluteDate(utcComponents, TimeScalesFactory.getUTC());
  47.  *   writeNextDate(date.getComponents(TimeScalesFactory.getTAI()));
  48.  * </pre>
  49.  *
  50.  * <p>Two complementary views are available:</p>
  51.  * <ul>
  52.  *   <li><p>location view (mainly for input/output or conversions)</p>
  53.  *   <p>locations represent the coordinate of one event with respect to a
  54.  *   {@link TimeScale time scale}. The related methods are {@link
  55.  *   #AbsoluteDate(DateComponents, TimeComponents, TimeScale)}, {@link
  56.  *   #AbsoluteDate(int, int, int, int, int, double, TimeScale)}, {@link
  57.  *   #AbsoluteDate(int, int, int, TimeScale)}, {@link #AbsoluteDate(Date,
  58.  *   TimeScale)}, {@link #parseCCSDSCalendarSegmentedTimeCode(byte, byte[])},
  59.  *   {@link #toDate(TimeScale)}, {@link #toString(TimeScale) toString(timeScale)},
  60.  *   {@link #toString()}, and {@link #timeScalesOffset}.</p>
  61.  *   </li>
  62.  *   <li><p>offset view (mainly for physical computation)</p>
  63.  *   <p>offsets represent either the flow of time between two events
  64.  *   (two instances of the class) or durations. They are counted in seconds,
  65.  *   are continuous and could be measured using only a virtually perfect stopwatch.
  66.  *   The related methods are {@link #AbsoluteDate(AbsoluteDate, double)},
  67.  *   {@link #parseCCSDSUnsegmentedTimeCode(byte, byte, byte[], AbsoluteDate)},
  68.  *   {@link #parseCCSDSDaySegmentedTimeCode(byte, byte[], DateComponents)},
  69.  *   {@link #durationFrom(AbsoluteDate)}, {@link #compareTo(AbsoluteDate)}, {@link #equals(Object)}
  70.  *   and {@link #hashCode()}.</p>
  71.  *   </li>
  72.  * </ul>
  73.  * <p>
  74.  * A few reference epochs which are commonly used in space systems have been defined. These
  75.  * epochs can be used as the basis for offset computation. The supported epochs are:
  76.  * {@link #JULIAN_EPOCH}, {@link #MODIFIED_JULIAN_EPOCH}, {@link #FIFTIES_EPOCH},
  77.  * {@link #CCSDS_EPOCH}, {@link #GALILEO_EPOCH}, {@link #GPS_EPOCH}, {@link #QZSS_EPOCH}
  78.  * {@link #J2000_EPOCH}, {@link #JAVA_EPOCH}.
  79.  * There are also two factory methods {@link #createJulianEpoch(double)}
  80.  * and {@link #createBesselianEpoch(double)} that can be used to compute other reference
  81.  * epochs like J1900.0 or B1950.0.
  82.  * In addition to these reference epochs, two other constants are defined for convenience:
  83.  * {@link #PAST_INFINITY} and {@link #FUTURE_INFINITY}, which can be used either as dummy
  84.  * dates when a date is not yet initialized, or for initialization of loops searching for
  85.  * a min or max date.
  86.  * </p>
  87.  * <p>
  88.  * Instances of the <code>AbsoluteDate</code> class are guaranteed to be immutable.
  89.  * </p>
  90.  * @author Luc Maisonobe
  91.  * @author Evan Ward
  92.  * @see TimeScale
  93.  * @see TimeStamped
  94.  * @see ChronologicalComparator
  95.  */
  96. public class AbsoluteDate
  97.     implements TimeStamped, TimeShiftable<AbsoluteDate>, Comparable<AbsoluteDate>, Serializable {

  98.     /** Reference epoch for julian dates: -4712-01-01T12:00:00 Terrestrial Time.
  99.      * <p>Both <code>java.util.Date</code> and {@link DateComponents} classes
  100.      * follow the astronomical conventions and consider a year 0 between
  101.      * years -1 and +1, hence this reference date lies in year -4712 and not
  102.      * in year -4713 as can be seen in other documents or programs that obey
  103.      * a different convention (for example the <code>convcal</code> utility).</p>
  104.      *
  105.      * <p>This constant uses the {@link DataContext#getDefault() default data context}.
  106.      *
  107.      * @see TimeScales#getJulianEpoch()
  108.      */
  109.     @DefaultDataContext
  110.     public static final AbsoluteDate JULIAN_EPOCH =
  111.             DataContext.getDefault().getTimeScales().getJulianEpoch();

  112.     /** Reference epoch for modified julian dates: 1858-11-17T00:00:00 Terrestrial Time.
  113.      *
  114.      * <p>This constant uses the {@link DataContext#getDefault() default data context}.
  115.      *
  116.      * @see TimeScales#getModifiedJulianEpoch()
  117.      */
  118.     @DefaultDataContext
  119.     public static final AbsoluteDate MODIFIED_JULIAN_EPOCH =
  120.             DataContext.getDefault().getTimeScales().getModifiedJulianEpoch();

  121.     /** Reference epoch for 1950 dates: 1950-01-01T00:00:00 Terrestrial Time.
  122.      *
  123.      * <p>This constant uses the {@link DataContext#getDefault() default data context}.
  124.      *
  125.      * @see TimeScales#getFiftiesEpoch()
  126.      */
  127.     @DefaultDataContext
  128.     public static final AbsoluteDate FIFTIES_EPOCH =
  129.             DataContext.getDefault().getTimeScales().getFiftiesEpoch();

  130.     /** Reference epoch for CCSDS Time Code Format (CCSDS 301.0-B-4):
  131.      * 1958-01-01T00:00:00 International Atomic Time (<em>not</em> UTC).
  132.      *
  133.      * <p>This constant uses the {@link DataContext#getDefault() default data context}.
  134.      *
  135.      * @see TimeScales#getCcsdsEpoch()
  136.      */
  137.     @DefaultDataContext
  138.     public static final AbsoluteDate CCSDS_EPOCH =
  139.             DataContext.getDefault().getTimeScales().getCcsdsEpoch();

  140.     /** Reference epoch for Galileo System Time: 1999-08-22T00:00:00 GST.
  141.      *
  142.      * <p>This constant uses the {@link DataContext#getDefault() default data context}.
  143.      *
  144.      * @see TimeScales#getGalileoEpoch()
  145.      */
  146.     @DefaultDataContext
  147.     public static final AbsoluteDate GALILEO_EPOCH =
  148.             DataContext.getDefault().getTimeScales().getGalileoEpoch();

  149.     /** Reference epoch for GPS weeks: 1980-01-06T00:00:00 GPS time.
  150.      *
  151.      * <p>This constant uses the {@link DataContext#getDefault() default data context}.
  152.      *
  153.      * @see TimeScales#getGpsEpoch()
  154.      */
  155.     @DefaultDataContext
  156.     public static final AbsoluteDate GPS_EPOCH =
  157.             DataContext.getDefault().getTimeScales().getGpsEpoch();

  158.     /** Reference epoch for QZSS weeks: 1980-01-06T00:00:00 QZSS time.
  159.      *
  160.      * <p>This constant uses the {@link DataContext#getDefault() default data context}.
  161.      *
  162.      * @see TimeScales#getQzssEpoch()
  163.      */
  164.     @DefaultDataContext
  165.     public static final AbsoluteDate QZSS_EPOCH =
  166.             DataContext.getDefault().getTimeScales().getQzssEpoch();

  167.     /** Reference epoch for IRNSS weeks: 1999-08-22T00:00:00 IRNSS time.
  168.      *
  169.      * <p>This constant uses the {@link DataContext#getDefault() default data context}.
  170.      *
  171.      * @see TimeScales#getIrnssEpoch()
  172.      */
  173.     @DefaultDataContext
  174.     public static final AbsoluteDate IRNSS_EPOCH =
  175.             DataContext.getDefault().getTimeScales().getIrnssEpoch();

  176.     /** Reference epoch for BeiDou weeks: 2006-01-01T00:00:00 UTC.
  177.      *
  178.      * <p>This constant uses the {@link DataContext#getDefault() default data context}.
  179.      *
  180.      * @see TimeScales#getBeidouEpoch()
  181.      */
  182.     @DefaultDataContext
  183.     public static final AbsoluteDate BEIDOU_EPOCH =
  184.             DataContext.getDefault().getTimeScales().getBeidouEpoch();

  185.     /** Reference epoch for GLONASS four-year interval number: 1996-01-01T00:00:00 GLONASS time.
  186.      * <p>By convention, TGLONASS = UTC + 3 hours.</p>
  187.      *
  188.      * <p>This constant uses the {@link DataContext#getDefault() default data context}.
  189.      *
  190.      * @see TimeScales#getGlonassEpoch()
  191.      */
  192.     @DefaultDataContext
  193.     public static final AbsoluteDate GLONASS_EPOCH =
  194.             DataContext.getDefault().getTimeScales().getGlonassEpoch();

  195.     /** J2000.0 Reference epoch: 2000-01-01T12:00:00 Terrestrial Time (<em>not</em> UTC).
  196.      * @see #createJulianEpoch(double)
  197.      * @see #createBesselianEpoch(double)
  198.      *
  199.      * <p>This constant uses the {@link DataContext#getDefault() default data context}.
  200.      *
  201.      * @see TimeScales#getJ2000Epoch()
  202.      */
  203.     @DefaultDataContext
  204.     public static final AbsoluteDate J2000_EPOCH = // TODO
  205.             DataContext.getDefault().getTimeScales().getJ2000Epoch();

  206.     /** Java Reference epoch: 1970-01-01T00:00:00 Universal Time Coordinate.
  207.      * <p>
  208.      * Between 1968-02-01 and 1972-01-01, UTC-TAI = 4.213 170 0s + (MJD - 39 126) x 0.002 592s.
  209.      * As on 1970-01-01 MJD = 40587, UTC-TAI = 8.000082s
  210.      * </p>
  211.      *
  212.      * <p>This constant uses the {@link DataContext#getDefault() default data context}.
  213.      *
  214.      * @see TimeScales#getJavaEpoch()
  215.      */
  216.     @DefaultDataContext
  217.     public static final AbsoluteDate JAVA_EPOCH =
  218.             DataContext.getDefault().getTimeScales().getJavaEpoch();

  219.     /**
  220.      * An arbitrary finite date. Uses when a non-null date is needed but its value doesn't
  221.      * matter.
  222.      */
  223.     public static final AbsoluteDate ARBITRARY_EPOCH = new AbsoluteDate(0, 0);

  224.     /** Dummy date at infinity in the past direction.
  225.      * @see TimeScales#getPastInfinity()
  226.      */
  227.     public static final AbsoluteDate PAST_INFINITY = ARBITRARY_EPOCH.shiftedBy(Double.NEGATIVE_INFINITY);

  228.     /** Dummy date at infinity in the future direction.
  229.      * @see TimeScales#getFutureInfinity()
  230.      */
  231.     public static final AbsoluteDate FUTURE_INFINITY = ARBITRARY_EPOCH.shiftedBy(Double.POSITIVE_INFINITY);

  232.     /** Serializable UID. */
  233.     private static final long serialVersionUID = 617061803741806846L;

  234.     /** Reference epoch in seconds from 2000-01-01T12:00:00 TAI.
  235.      * <p>Beware, it is not {@link #J2000_EPOCH} since it is in TAI and not in TT.</p> */
  236.     private final long epoch;

  237.     /** Offset from the reference epoch in seconds. */
  238.     private final double offset;

  239.     /** Create an instance with a default value ({@link #J2000_EPOCH}).
  240.      *
  241.      * <p>This constructor uses the {@link DataContext#getDefault() default data context}.
  242.      *
  243.      * @see #AbsoluteDate(DateTimeComponents, TimeScale)
  244.      */
  245.     @DefaultDataContext
  246.     public AbsoluteDate() {
  247.         epoch  = J2000_EPOCH.epoch;
  248.         offset = J2000_EPOCH.offset;
  249.     }

  250.     /** Build an instance from a location (parsed from a string) in a {@link TimeScale time scale}.
  251.      * <p>
  252.      * The supported formats for location are mainly the ones defined in ISO-8601 standard,
  253.      * the exact subset is explained in {@link DateTimeComponents#parseDateTime(String)},
  254.      * {@link DateComponents#parseDate(String)} and {@link TimeComponents#parseTime(String)}.
  255.      * </p>
  256.      * <p>
  257.      * As CCSDS ASCII calendar segmented time code is a trimmed down version of ISO-8601,
  258.      * it is also supported by this constructor.
  259.      * </p>
  260.      * @param location location in the time scale, must be in a supported format
  261.      * @param timeScale time scale
  262.      * @exception IllegalArgumentException if location string is not in a supported format
  263.      */
  264.     public AbsoluteDate(final String location, final TimeScale timeScale) {
  265.         this(DateTimeComponents.parseDateTime(location), timeScale);
  266.     }

  267.     /** Build an instance from a location in a {@link TimeScale time scale}.
  268.      * @param location location in the time scale
  269.      * @param timeScale time scale
  270.      */
  271.     public AbsoluteDate(final DateTimeComponents location, final TimeScale timeScale) {
  272.         this(location.getDate(), location.getTime(), timeScale);
  273.     }

  274.     /** Build an instance from a location in a {@link TimeScale time scale}.
  275.      * @param date date location in the time scale
  276.      * @param time time location in the time scale
  277.      * @param timeScale time scale
  278.      */
  279.     public AbsoluteDate(final DateComponents date, final TimeComponents time,
  280.                         final TimeScale timeScale) {

  281.         final double seconds  = time.getSecond();
  282.         final double tsOffset = timeScale.offsetToTAI(date, time);

  283.         // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
  284.         // the following statements must NOT be simplified, they rely on floating point
  285.         // arithmetic properties (rounding and representable numbers)
  286.         // at the end, the EXACT result of addition seconds + tsOffset
  287.         // is sum + residual, where sum is the closest representable number to the exact
  288.         // result and residual is the missing part that does not fit in the first number
  289.         final double sum      = seconds + tsOffset;
  290.         final double sPrime   = sum - tsOffset;
  291.         final double tPrime   = sum - sPrime;
  292.         final double deltaS   = seconds  - sPrime;
  293.         final double deltaT   = tsOffset - tPrime;
  294.         final double residual = deltaS   + deltaT;
  295.         final long   dl       = (long) FastMath.floor(sum);

  296.         offset = (sum - dl) + residual;
  297.         epoch  = 60l * ((date.getJ2000Day() * 24l + time.getHour()) * 60l +
  298.                         time.getMinute() - time.getMinutesFromUTC() - 720l) + dl;

  299.     }

  300.     /** Build an instance from a location in a {@link TimeScale time scale}.
  301.      * @param year year number (may be 0 or negative for BC years)
  302.      * @param month month number from 1 to 12
  303.      * @param day day number from 1 to 31
  304.      * @param hour hour number from 0 to 23
  305.      * @param minute minute number from 0 to 59
  306.      * @param second second number from 0.0 to 60.0 (excluded)
  307.      * @param timeScale time scale
  308.      * @exception IllegalArgumentException if inconsistent arguments
  309.      * are given (parameters out of range)
  310.      */
  311.     public AbsoluteDate(final int year, final int month, final int day,
  312.                         final int hour, final int minute, final double second,
  313.                         final TimeScale timeScale) throws IllegalArgumentException {
  314.         this(new DateComponents(year, month, day), new TimeComponents(hour, minute, second), timeScale);
  315.     }

  316.     /** Build an instance from a location in a {@link TimeScale time scale}.
  317.      * @param year year number (may be 0 or negative for BC years)
  318.      * @param month month enumerate
  319.      * @param day day number from 1 to 31
  320.      * @param hour hour number from 0 to 23
  321.      * @param minute minute number from 0 to 59
  322.      * @param second second number from 0.0 to 60.0 (excluded)
  323.      * @param timeScale time scale
  324.      * @exception IllegalArgumentException if inconsistent arguments
  325.      * are given (parameters out of range)
  326.      */
  327.     public AbsoluteDate(final int year, final Month month, final int day,
  328.                         final int hour, final int minute, final double second,
  329.                         final TimeScale timeScale) throws IllegalArgumentException {
  330.         this(new DateComponents(year, month, day), new TimeComponents(hour, minute, second), timeScale);
  331.     }

  332.     /** Build an instance from a location in a {@link TimeScale time scale}.
  333.      * <p>The hour is set to 00:00:00.000.</p>
  334.      * @param date date location in the time scale
  335.      * @param timeScale time scale
  336.      * @exception IllegalArgumentException if inconsistent arguments
  337.      * are given (parameters out of range)
  338.      */
  339.     public AbsoluteDate(final DateComponents date, final TimeScale timeScale)
  340.         throws IllegalArgumentException {
  341.         this(date, TimeComponents.H00, timeScale);
  342.     }

  343.     /** Build an instance from a location in a {@link TimeScale time scale}.
  344.      * <p>The hour is set to 00:00:00.000.</p>
  345.      * @param year year number (may be 0 or negative for BC years)
  346.      * @param month month number from 1 to 12
  347.      * @param day day number from 1 to 31
  348.      * @param timeScale time scale
  349.      * @exception IllegalArgumentException if inconsistent arguments
  350.      * are given (parameters out of range)
  351.      */
  352.     public AbsoluteDate(final int year, final int month, final int day,
  353.                         final TimeScale timeScale) throws IllegalArgumentException {
  354.         this(new DateComponents(year, month, day), TimeComponents.H00, timeScale);
  355.     }

  356.     /** Build an instance from a location in a {@link TimeScale time scale}.
  357.      * <p>The hour is set to 00:00:00.000.</p>
  358.      * @param year year number (may be 0 or negative for BC years)
  359.      * @param month month enumerate
  360.      * @param day day number from 1 to 31
  361.      * @param timeScale time scale
  362.      * @exception IllegalArgumentException if inconsistent arguments
  363.      * are given (parameters out of range)
  364.      */
  365.     public AbsoluteDate(final int year, final Month month, final int day,
  366.                         final TimeScale timeScale) throws IllegalArgumentException {
  367.         this(new DateComponents(year, month, day), TimeComponents.H00, timeScale);
  368.     }

  369.     /** Build an instance from a location in a {@link TimeScale time scale}.
  370.      * @param location location in the time scale
  371.      * @param timeScale time scale
  372.      */
  373.     public AbsoluteDate(final Date location, final TimeScale timeScale) {
  374.         this(new DateComponents(DateComponents.JAVA_EPOCH,
  375.                                 (int) (location.getTime() / 86400000l)),
  376.                                  millisToTimeComponents((int) (location.getTime() % 86400000l)),
  377.              timeScale);
  378.     }

  379.     /** Build an instance from an elapsed duration since to another instant.
  380.      * <p>It is important to note that the elapsed duration is <em>not</em>
  381.      * the difference between two readings on a time scale. As an example,
  382.      * the duration between the two instants leading to the readings
  383.      * 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the {@link UTCScale UTC}
  384.      * time scale is <em>not</em> 1 second, but a stop watch would have measured
  385.      * an elapsed duration of 2 seconds between these two instances because a leap
  386.      * second was introduced at the end of 2005 in this time scale.</p>
  387.      * <p>This constructor is the reverse of the {@link #durationFrom(AbsoluteDate)}
  388.      * method.</p>
  389.      * @param since start instant of the measured duration
  390.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  391.      * instant, as measured in a regular time scale
  392.      * @see #durationFrom(AbsoluteDate)
  393.      */
  394.     public AbsoluteDate(final AbsoluteDate since, final double elapsedDuration) {

  395.         final double sum = since.offset + elapsedDuration;
  396.         if (Double.isInfinite(sum)) {
  397.             offset = sum;
  398.             epoch  = (sum < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
  399.         } else {
  400.             // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
  401.             // the following statements must NOT be simplified, they rely on floating point
  402.             // arithmetic properties (rounding and representable numbers)
  403.             // at the end, the EXACT result of addition since.offset + elapsedDuration
  404.             // is sum + residual, where sum is the closest representable number to the exact
  405.             // result and residual is the missing part that does not fit in the first number
  406.             final double oPrime   = sum - elapsedDuration;
  407.             final double dPrime   = sum - oPrime;
  408.             final double deltaO   = since.offset - oPrime;
  409.             final double deltaD   = elapsedDuration - dPrime;
  410.             final double residual = deltaO + deltaD;
  411.             final long   dl       = (long) FastMath.floor(sum);
  412.             offset = (sum - dl) + residual;
  413.             epoch  = since.epoch  + dl;
  414.         }
  415.     }

  416.     /** Build an instance from an apparent clock offset with respect to another
  417.      * instant <em>in the perspective of a specific {@link TimeScale time scale}</em>.
  418.      * <p>It is important to note that the apparent clock offset <em>is</em> the
  419.      * difference between two readings on a time scale and <em>not</em> an elapsed
  420.      * duration. As an example, the apparent clock offset between the two instants
  421.      * leading to the readings 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the
  422.      * {@link UTCScale UTC} time scale is 1 second, but the elapsed duration is 2
  423.      * seconds because a leap second has been introduced at the end of 2005 in this
  424.      * time scale.</p>
  425.      * <p>This constructor is the reverse of the {@link #offsetFrom(AbsoluteDate,
  426.      * TimeScale)} method.</p>
  427.      * @param reference reference instant
  428.      * @param apparentOffset apparent clock offset from the reference instant
  429.      * (difference between two readings in the specified time scale)
  430.      * @param timeScale time scale with respect to which the offset is defined
  431.      * @see #offsetFrom(AbsoluteDate, TimeScale)
  432.      */
  433.     public AbsoluteDate(final AbsoluteDate reference, final double apparentOffset,
  434.                         final TimeScale timeScale) {
  435.         this(new DateTimeComponents(reference.getComponents(timeScale), apparentOffset),
  436.              timeScale);
  437.     }

  438.     /** Build a date from its internal components.
  439.      * <p>
  440.      * This method is reserved for internal used (for example by {@link FieldAbsoluteDate}).
  441.      * </p>
  442.      * @param epoch reference epoch in seconds from 2000-01-01T12:00:00 TAI.
  443.      * (beware, it is not {@link #J2000_EPOCH} since it is in TAI and not in TT)
  444.      * @param offset offset from the reference epoch in seconds (must be
  445.      * between 0.0 included and 1.0 excluded)
  446.      * @since 9.0
  447.      */
  448.     AbsoluteDate(final long epoch, final double offset) {
  449.         this.epoch  = epoch;
  450.         this.offset = offset;
  451.     }

  452.     /** Extract time components from a number of milliseconds within the day.
  453.      * @param millisInDay number of milliseconds within the day
  454.      * @return time components
  455.      */
  456.     private static TimeComponents millisToTimeComponents(final int millisInDay) {
  457.         return new TimeComponents(millisInDay / 1000, 0.001 * (millisInDay % 1000));
  458.     }

  459.     /** Get the reference epoch in seconds from 2000-01-01T12:00:00 TAI.
  460.      * <p>
  461.      * This method is reserved for internal used (for example by {@link FieldAbsoluteDate}).
  462.      * </p>
  463.      * <p>
  464.      * Beware, it is not {@link #J2000_EPOCH} since it is in TAI and not in TT.
  465.      * </p>
  466.      * @return reference epoch in seconds from 2000-01-01T12:00:00 TAI
  467.      * @since 9.0
  468.      */
  469.     long getEpoch() {
  470.         return epoch;
  471.     }

  472.     /** Get the offset from the reference epoch in seconds.
  473.      * <p>
  474.      * This method is reserved for internal used (for example by {@link FieldAbsoluteDate}).
  475.      * </p>
  476.      * @return offset from the reference epoch in seconds
  477.      * @since 9.0
  478.      */
  479.     double getOffset() {
  480.         return offset;
  481.     }

  482.     /** Build an instance from a CCSDS Unsegmented Time Code (CUC).
  483.      * <p>
  484.      * CCSDS Unsegmented Time Code is defined in the blue book:
  485.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  486.      * </p>
  487.      * <p>
  488.      * If the date to be parsed is formatted using version 3 of the standard
  489.      * (CCSDS 301.0-B-3 published in 2002) or if the extension of the preamble
  490.      * field introduced in version 4 of the standard is not used, then the
  491.      * {@code preambleField2} parameter can be set to 0.
  492.      * </p>
  493.      *
  494.      * <p>This method uses the {@link DataContext#getDefault() default data context} if
  495.      * the CCSDS epoch is used.
  496.      *
  497.      * @param preambleField1 first byte of the field specifying the format, often
  498.      * not transmitted in data interfaces, as it is constant for a given data interface
  499.      * @param preambleField2 second byte of the field specifying the format
  500.      * (added in revision 4 of the CCSDS standard in 2010), often not transmitted in data
  501.      * interfaces, as it is constant for a given data interface (value ignored if presence
  502.      * not signaled in {@code preambleField1})
  503.      * @param timeField byte array containing the time code
  504.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  505.      * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
  506.      * may be null in this case)
  507.      * @return an instance corresponding to the specified date
  508.      * @see #parseCCSDSUnsegmentedTimeCode(byte, byte, byte[], AbsoluteDate, AbsoluteDate)
  509.      */
  510.     @DefaultDataContext
  511.     public static AbsoluteDate parseCCSDSUnsegmentedTimeCode(final byte preambleField1,
  512.                                                              final byte preambleField2,
  513.                                                              final byte[] timeField,
  514.                                                              final AbsoluteDate agencyDefinedEpoch) {
  515.         return parseCCSDSUnsegmentedTimeCode(preambleField1, preambleField2, timeField,
  516.                 agencyDefinedEpoch,
  517.                 DataContext.getDefault().getTimeScales().getCcsdsEpoch());
  518.     }

  519.     /**
  520.      * Build an instance from a CCSDS Unsegmented Time Code (CUC).
  521.      * <p>
  522.      * CCSDS Unsegmented Time Code is defined in the blue book: CCSDS Time Code Format
  523.      * (CCSDS 301.0-B-4) published in November 2010
  524.      * </p>
  525.      * <p>
  526.      * If the date to be parsed is formatted using version 3 of the standard (CCSDS
  527.      * 301.0-B-3 published in 2002) or if the extension of the preamble field introduced
  528.      * in version 4 of the standard is not used, then the {@code preambleField2} parameter
  529.      * can be set to 0.
  530.      * </p>
  531.      *
  532.      * @param preambleField1     first byte of the field specifying the format, often not
  533.      *                           transmitted in data interfaces, as it is constant for a
  534.      *                           given data interface
  535.      * @param preambleField2     second byte of the field specifying the format (added in
  536.      *                           revision 4 of the CCSDS standard in 2010), often not
  537.      *                           transmitted in data interfaces, as it is constant for a
  538.      *                           given data interface (value ignored if presence not
  539.      *                           signaled in {@code preambleField1})
  540.      * @param timeField          byte array containing the time code
  541.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field specifies
  542.      *                           the {@link #CCSDS_EPOCH CCSDS reference epoch} is used
  543.      *                           (and hence may be null in this case)
  544.      * @param ccsdsEpoch         reference epoch, ignored if the preamble field specifies
  545.      *                           the agency epoch is used.
  546.      * @return an instance corresponding to the specified date
  547.      * @since 10.1
  548.      */
  549.     public static AbsoluteDate parseCCSDSUnsegmentedTimeCode(
  550.             final byte preambleField1,
  551.             final byte preambleField2,
  552.             final byte[] timeField,
  553.             final AbsoluteDate agencyDefinedEpoch,
  554.             final AbsoluteDate ccsdsEpoch) {

  555.         // time code identification and reference epoch
  556.         final AbsoluteDate epoch;
  557.         switch (preambleField1 & 0x70) {
  558.             case 0x10:
  559.                 // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  560.                 epoch = ccsdsEpoch;
  561.                 break;
  562.             case 0x20:
  563.                 // the reference epoch is agency defined
  564.                 if (agencyDefinedEpoch == null) {
  565.                     throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  566.                 }
  567.                 epoch = agencyDefinedEpoch;
  568.                 break;
  569.             default :
  570.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  571.                                           formatByte(preambleField1));
  572.         }

  573.         // time field lengths
  574.         int coarseTimeLength = 1 + ((preambleField1 & 0x0C) >>> 2);
  575.         int fineTimeLength   = preambleField1 & 0x03;

  576.         if ((preambleField1 & 0x80) != 0x0) {
  577.             // there is an additional octet in preamble field
  578.             coarseTimeLength += (preambleField2 & 0x60) >>> 5;
  579.             fineTimeLength   += (preambleField2 & 0x1C) >>> 2;
  580.         }

  581.         if (timeField.length != coarseTimeLength + fineTimeLength) {
  582.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  583.                                       timeField.length, coarseTimeLength + fineTimeLength);
  584.         }

  585.         double seconds = 0;
  586.         for (int i = 0; i < coarseTimeLength; ++i) {
  587.             seconds = seconds * 256 + toUnsigned(timeField[i]);
  588.         }
  589.         double subseconds = 0;
  590.         for (int i = timeField.length - 1; i >= coarseTimeLength; --i) {
  591.             subseconds = (subseconds + toUnsigned(timeField[i])) / 256;
  592.         }

  593.         return new AbsoluteDate(epoch, seconds).shiftedBy(subseconds);

  594.     }

  595.     /** Build an instance from a CCSDS Day Segmented Time Code (CDS).
  596.      * <p>
  597.      * CCSDS Day Segmented Time Code is defined in the blue book:
  598.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  599.      * </p>
  600.      *
  601.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  602.      *
  603.      * @param preambleField field specifying the format, often not transmitted in
  604.      * data interfaces, as it is constant for a given data interface
  605.      * @param timeField byte array containing the time code
  606.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  607.      * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
  608.      * may be null in this case)
  609.      * @return an instance corresponding to the specified date
  610.      * @see #parseCCSDSDaySegmentedTimeCode(byte, byte[], DateComponents, TimeScale)
  611.      */
  612.     @DefaultDataContext
  613.     public static AbsoluteDate parseCCSDSDaySegmentedTimeCode(final byte preambleField, final byte[] timeField,
  614.                                                               final DateComponents agencyDefinedEpoch) {
  615.         return parseCCSDSDaySegmentedTimeCode(preambleField, timeField,
  616.                 agencyDefinedEpoch, DataContext.getDefault().getTimeScales().getUTC());
  617.     }

  618.     /** Build an instance from a CCSDS Day Segmented Time Code (CDS).
  619.      * <p>
  620.      * CCSDS Day Segmented Time Code is defined in the blue book:
  621.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  622.      * </p>
  623.      * @param preambleField field specifying the format, often not transmitted in
  624.      * data interfaces, as it is constant for a given data interface
  625.      * @param timeField byte array containing the time code
  626.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  627.      * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
  628.      * may be null in this case)
  629.      * @param utc      time scale used to compute date and time components.
  630.      * @return an instance corresponding to the specified date
  631.      * @since 10.1
  632.      */
  633.     public static AbsoluteDate parseCCSDSDaySegmentedTimeCode(
  634.             final byte preambleField,
  635.             final byte[] timeField,
  636.             final DateComponents agencyDefinedEpoch,
  637.             final TimeScale utc) {

  638.         // time code identification
  639.         if ((preambleField & 0xF0) != 0x40) {
  640.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  641.                                       formatByte(preambleField));
  642.         }

  643.         // reference epoch
  644.         final DateComponents epoch;
  645.         if ((preambleField & 0x08) == 0x00) {
  646.             // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  647.             epoch = DateComponents.CCSDS_EPOCH;
  648.         } else {
  649.             // the reference epoch is agency defined
  650.             if (agencyDefinedEpoch == null) {
  651.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  652.             }
  653.             epoch = agencyDefinedEpoch;
  654.         }

  655.         // time field lengths
  656.         final int daySegmentLength = ((preambleField & 0x04) == 0x0) ? 2 : 3;
  657.         final int subMillisecondLength = (preambleField & 0x03) << 1;
  658.         if (subMillisecondLength == 6) {
  659.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  660.                                       formatByte(preambleField));
  661.         }
  662.         if (timeField.length != daySegmentLength + 4 + subMillisecondLength) {
  663.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  664.                                       timeField.length, daySegmentLength + 4 + subMillisecondLength);
  665.         }


  666.         int i   = 0;
  667.         int day = 0;
  668.         while (i < daySegmentLength) {
  669.             day = day * 256 + toUnsigned(timeField[i++]);
  670.         }

  671.         long milliInDay = 0l;
  672.         while (i < daySegmentLength + 4) {
  673.             milliInDay = milliInDay * 256 + toUnsigned(timeField[i++]);
  674.         }
  675.         final int milli   = (int) (milliInDay % 1000l);
  676.         final int seconds = (int) ((milliInDay - milli) / 1000l);

  677.         double subMilli = 0;
  678.         double divisor  = 1;
  679.         while (i < timeField.length) {
  680.             subMilli = subMilli * 256 + toUnsigned(timeField[i++]);
  681.             divisor *= 1000;
  682.         }

  683.         final DateComponents date = new DateComponents(epoch, day);
  684.         final TimeComponents time = new TimeComponents(seconds);
  685.         return new AbsoluteDate(date, time, utc).shiftedBy(milli * 1.0e-3 + subMilli / divisor);

  686.     }

  687.     /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  688.      * <p>
  689.      * CCSDS Calendar Segmented Time Code is defined in the blue book:
  690.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  691.      * </p>
  692.      *
  693.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  694.      *
  695.      * @param preambleField field specifying the format, often not transmitted in
  696.      * data interfaces, as it is constant for a given data interface
  697.      * @param timeField byte array containing the time code
  698.      * @return an instance corresponding to the specified date
  699.      * @see #parseCCSDSCalendarSegmentedTimeCode(byte, byte[], TimeScale)
  700.      */
  701.     @DefaultDataContext
  702.     public static AbsoluteDate parseCCSDSCalendarSegmentedTimeCode(final byte preambleField, final byte[] timeField) {
  703.         return parseCCSDSCalendarSegmentedTimeCode(preambleField, timeField,
  704.                 DataContext.getDefault().getTimeScales().getUTC());
  705.     }

  706.     /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  707.      * <p>
  708.      * CCSDS Calendar Segmented Time Code is defined in the blue book:
  709.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  710.      * </p>
  711.      * @param preambleField field specifying the format, often not transmitted in
  712.      * data interfaces, as it is constant for a given data interface
  713.      * @param timeField byte array containing the time code
  714.      * @param utc      time scale used to compute date and time components.
  715.      * @return an instance corresponding to the specified date
  716.      * @since 10.1
  717.      */
  718.     public static AbsoluteDate parseCCSDSCalendarSegmentedTimeCode(
  719.             final byte preambleField,
  720.             final byte[] timeField,
  721.             final TimeScale utc) {

  722.         // time code identification
  723.         if ((preambleField & 0xF0) != 0x50) {
  724.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  725.                                       formatByte(preambleField));
  726.         }

  727.         // time field length
  728.         final int length = 7 + (preambleField & 0x07);
  729.         if (length == 14) {
  730.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  731.                                       formatByte(preambleField));
  732.         }
  733.         if (timeField.length != length) {
  734.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  735.                                       timeField.length, length);
  736.         }

  737.         // date part in the first four bytes
  738.         final DateComponents date;
  739.         if ((preambleField & 0x08) == 0x00) {
  740.             // month of year and day of month variation
  741.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  742.                                       toUnsigned(timeField[2]),
  743.                                       toUnsigned(timeField[3]));
  744.         } else {
  745.             // day of year variation
  746.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  747.                                       toUnsigned(timeField[2]) * 256 + toUnsigned(timeField[3]));
  748.         }

  749.         // time part from bytes 5 to last (between 7 and 13 depending on precision)
  750.         final TimeComponents time = new TimeComponents(toUnsigned(timeField[4]),
  751.                                                        toUnsigned(timeField[5]),
  752.                                                        toUnsigned(timeField[6]));
  753.         double subSecond = 0;
  754.         double divisor   = 1;
  755.         for (int i = 7; i < length; ++i) {
  756.             subSecond = subSecond * 100 + toUnsigned(timeField[i]);
  757.             divisor *= 100;
  758.         }

  759.         return new AbsoluteDate(date, time, utc).shiftedBy(subSecond / divisor);

  760.     }

  761.     /** Decode a signed byte as an unsigned int value.
  762.      * @param b byte to decode
  763.      * @return an unsigned int value
  764.      */
  765.     private static int toUnsigned(final byte b) {
  766.         final int i = (int) b;
  767.         return (i < 0) ? 256 + i : i;
  768.     }

  769.     /** Format a byte as an hex string for error messages.
  770.      * @param data byte to format
  771.      * @return a formatted string
  772.      */
  773.     private static String formatByte(final byte data) {
  774.         return "0x" + Integer.toHexString(data).toUpperCase();
  775.     }

  776.     /** Build an instance corresponding to a Julian Day date.
  777.      * @param jd Julian day
  778.      * @param secondsSinceNoon seconds in the Julian day
  779.      * (BEWARE, Julian days start at noon, so 0.0 is noon)
  780.      * @param timeScale time scale in which the seconds in day are defined
  781.      * @return a new instant
  782.      */
  783.     public static AbsoluteDate createJDDate(final int jd, final double secondsSinceNoon,
  784.                                              final TimeScale timeScale) {
  785.         return new AbsoluteDate(new DateComponents(DateComponents.JULIAN_EPOCH, jd),
  786.                                 TimeComponents.H12, timeScale).shiftedBy(secondsSinceNoon);
  787.     }

  788.     /** Build an instance corresponding to a Modified Julian Day date.
  789.      * @param mjd modified Julian day
  790.      * @param secondsInDay seconds in the day
  791.      * @param timeScale time scale in which the seconds in day are defined
  792.      * @return a new instant
  793.      * @exception OrekitIllegalArgumentException if seconds number is out of range
  794.      */
  795.     public static AbsoluteDate createMJDDate(final int mjd, final double secondsInDay,
  796.                                              final TimeScale timeScale)
  797.         throws OrekitIllegalArgumentException {
  798.         final DateComponents dc = new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, mjd);
  799.         final TimeComponents tc;
  800.         if (secondsInDay >= Constants.JULIAN_DAY) {
  801.             // check we are really allowed to use this number of seconds
  802.             final int    secondsA = 86399; // 23:59:59, i.e. 59s in the last minute of the day
  803.             final double secondsB = secondsInDay - secondsA;
  804.             final TimeComponents safeTC = new TimeComponents(secondsA, 0.0);
  805.             final AbsoluteDate safeDate = new AbsoluteDate(dc, safeTC, timeScale);
  806.             if (timeScale.minuteDuration(safeDate) > 59 + secondsB) {
  807.                 // we are within the last minute of the day, the number of seconds is OK
  808.                 return safeDate.shiftedBy(secondsB);
  809.             } else {
  810.                 // let TimeComponents trigger an OrekitIllegalArgumentException
  811.                 // for the wrong number of seconds
  812.                 tc = new TimeComponents(secondsA, secondsB);
  813.             }
  814.         } else {
  815.             tc = new TimeComponents(secondsInDay);
  816.         }

  817.         // create the date
  818.         return new AbsoluteDate(dc, tc, timeScale);

  819.     }


  820.     /** Build an instance corresponding to a Julian Epoch (JE).
  821.      * <p>According to Lieske paper: <a
  822.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&amp;defaultprint=YES&amp;filetype=.pdf.">
  823.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
  824.      * vol. 73, no. 3, Mar. 1979, p. 282-284, Julian Epoch is related to Julian Ephemeris Date as:</p>
  825.      * <pre>
  826.      * JE = 2000.0 + (JED - 2451545.0) / 365.25
  827.      * </pre>
  828.      * <p>
  829.      * This method reverts the formula above and computes an {@code AbsoluteDate} from the Julian Epoch.
  830.      * </p>
  831.      *
  832.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  833.      *
  834.      * @param julianEpoch Julian epoch, like 2000.0 for defining the classical reference J2000.0
  835.      * @return a new instant
  836.      * @see #J2000_EPOCH
  837.      * @see #createBesselianEpoch(double)
  838.      * @see TimeScales#createJulianEpoch(double)
  839.      */
  840.     @DefaultDataContext
  841.     public static AbsoluteDate createJulianEpoch(final double julianEpoch) {
  842.         return DataContext.getDefault().getTimeScales().createJulianEpoch(julianEpoch);
  843.     }

  844.     /** Build an instance corresponding to a Besselian Epoch (BE).
  845.      * <p>According to Lieske paper: <a
  846.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&amp;defaultprint=YES&amp;filetype=.pdf.">
  847.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
  848.      * vol. 73, no. 3, Mar. 1979, p. 282-284, Besselian Epoch is related to Julian Ephemeris Date as:</p>
  849.      * <pre>
  850.      * BE = 1900.0 + (JED - 2415020.31352) / 365.242198781
  851.      * </pre>
  852.      * <p>
  853.      * This method reverts the formula above and computes an {@code AbsoluteDate} from the Besselian Epoch.
  854.      * </p>
  855.      *
  856.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  857.      *
  858.      * @param besselianEpoch Besselian epoch, like 1950 for defining the classical reference B1950.0
  859.      * @return a new instant
  860.      * @see #createJulianEpoch(double)
  861.      * @see TimeScales#createBesselianEpoch(double)
  862.      */
  863.     @DefaultDataContext
  864.     public static AbsoluteDate createBesselianEpoch(final double besselianEpoch) {
  865.         return DataContext.getDefault().getTimeScales()
  866.                 .createBesselianEpoch(besselianEpoch);
  867.     }

  868.     /** Get a time-shifted date.
  869.      * <p>
  870.      * Calling this method is equivalent to call <code>new AbsoluteDate(this, dt)</code>.
  871.      * </p>
  872.      * @param dt time shift in seconds
  873.      * @return a new date, shifted with respect to instance (which is immutable)
  874.      * @see org.orekit.utils.PVCoordinates#shiftedBy(double)
  875.      * @see org.orekit.attitudes.Attitude#shiftedBy(double)
  876.      * @see org.orekit.orbits.Orbit#shiftedBy(double)
  877.      * @see org.orekit.propagation.SpacecraftState#shiftedBy(double)
  878.      */
  879.     public AbsoluteDate shiftedBy(final double dt) {
  880.         return new AbsoluteDate(this, dt);
  881.     }

  882.     /** Compute the physically elapsed duration between two instants.
  883.      * <p>The returned duration is the number of seconds physically
  884.      * elapsed between the two instants, measured in a regular time
  885.      * scale with respect to surface of the Earth (i.e either the {@link
  886.      * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
  887.      * GPSScale GPS scale}). It is the only method that gives a
  888.      * duration with a physical meaning.</p>
  889.      * <p>This method gives the same result (with less computation)
  890.      * as calling {@link #offsetFrom(AbsoluteDate, TimeScale)}
  891.      * with a second argument set to one of the regular scales cited
  892.      * above.</p>
  893.      * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
  894.      * double)} constructor.</p>
  895.      * @param instant instant to subtract from the instance
  896.      * @return offset in seconds between the two instants (positive
  897.      * if the instance is posterior to the argument)
  898.      * @see #offsetFrom(AbsoluteDate, TimeScale)
  899.      * @see #AbsoluteDate(AbsoluteDate, double)
  900.      */
  901.     public double durationFrom(final AbsoluteDate instant) {
  902.         return (epoch - instant.epoch) + (offset - instant.offset);
  903.     }

  904.     /** Compute the apparent clock offset between two instant <em>in the
  905.      * perspective of a specific {@link TimeScale time scale}</em>.
  906.      * <p>The offset is the number of seconds counted in the given
  907.      * time scale between the locations of the two instants, with
  908.      * all time scale irregularities removed (i.e. considering all
  909.      * days are exactly 86400 seconds long). This method will give
  910.      * a result that may not have a physical meaning if the time scale
  911.      * is irregular. For example since a leap second was introduced at
  912.      * the end of 2005, the apparent offset between 2005-12-31T23:59:59
  913.      * and 2006-01-01T00:00:00 is 1 second, but the physical duration
  914.      * of the corresponding time interval as returned by the {@link
  915.      * #durationFrom(AbsoluteDate)} method is 2 seconds.</p>
  916.      * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
  917.      * double, TimeScale)} constructor.</p>
  918.      * @param instant instant to subtract from the instance
  919.      * @param timeScale time scale with respect to which the offset should
  920.      * be computed
  921.      * @return apparent clock offset in seconds between the two instants
  922.      * (positive if the instance is posterior to the argument)
  923.      * @see #durationFrom(AbsoluteDate)
  924.      * @see #AbsoluteDate(AbsoluteDate, double, TimeScale)
  925.      */
  926.     public double offsetFrom(final AbsoluteDate instant, final TimeScale timeScale) {
  927.         final long   elapsedDurationA = epoch - instant.epoch;
  928.         final double elapsedDurationB = (offset         + timeScale.offsetFromTAI(this)) -
  929.                                         (instant.offset + timeScale.offsetFromTAI(instant));
  930.         return  elapsedDurationA + elapsedDurationB;
  931.     }

  932.     /** Compute the offset between two time scales at the current instant.
  933.      * <p>The offset is defined as <i>l₁-l₂</i>
  934.      * where <i>l₁</i> is the location of the instant in
  935.      * the <code>scale1</code> time scale and <i>l₂</i> is the
  936.      * location of the instant in the <code>scale2</code> time scale.</p>
  937.      * @param scale1 first time scale
  938.      * @param scale2 second time scale
  939.      * @return offset in seconds between the two time scales at the
  940.      * current instant
  941.      */
  942.     public double timeScalesOffset(final TimeScale scale1, final TimeScale scale2) {
  943.         return scale1.offsetFromTAI(this) - scale2.offsetFromTAI(this);
  944.     }

  945.     /** Convert the instance to a Java {@link java.util.Date Date}.
  946.      * <p>Conversion to the Date class induces a loss of precision because
  947.      * the Date class does not provide sub-millisecond information. Java Dates
  948.      * are considered to be locations in some times scales.</p>
  949.      * @param timeScale time scale to use
  950.      * @return a {@link java.util.Date Date} instance representing the location
  951.      * of the instant in the time scale
  952.      */
  953.     public Date toDate(final TimeScale timeScale) {
  954.         final double time = epoch + (offset + timeScale.offsetFromTAI(this));
  955.         return new Date(FastMath.round((time + 10957.5 * 86400.0) * 1000));
  956.     }

  957.     /** Split the instance into date/time components.
  958.      * @param timeScale time scale to use
  959.      * @return date/time components
  960.      */
  961.     public DateTimeComponents getComponents(final TimeScale timeScale) {

  962.         if (Double.isInfinite(offset)) {
  963.             // special handling for past and future infinity
  964.             if (offset < 0) {
  965.                 return new DateTimeComponents(DateComponents.MIN_EPOCH, TimeComponents.H00);
  966.             } else {
  967.                 return new DateTimeComponents(DateComponents.MAX_EPOCH,
  968.                                               new TimeComponents(23, 59, 59.999));
  969.             }
  970.         }

  971.         // compute offset from 2000-01-01T00:00:00 in specified time scale exactly,
  972.         // using Møller-Knuth TwoSum algorithm without branching
  973.         // the following statements must NOT be simplified, they rely on floating point
  974.         // arithmetic properties (rounding and representable numbers)
  975.         // at the end, the EXACT result of addition offset + timeScale.offsetFromTAI(this)
  976.         // is sum + residual, where sum is the closest representable number to the exact
  977.         // result and residual is the missing part that does not fit in the first number
  978.         final double taiOffset = timeScale.offsetFromTAI(this);
  979.         final double sum       = offset + taiOffset;
  980.         final double oPrime    = sum - taiOffset;
  981.         final double dPrime    = sum - oPrime;
  982.         final double deltaO    = offset - oPrime;
  983.         final double deltaD    = taiOffset - dPrime;
  984.         final double residual  = deltaO + deltaD;

  985.         // split date and time
  986.         final long   carry = (long) FastMath.floor(sum);
  987.         double offset2000B = (sum - carry) + residual;
  988.         long   offset2000A = epoch + carry + 43200l;
  989.         if (offset2000B < 0) {
  990.             offset2000A -= 1;
  991.             offset2000B += 1;
  992.         }
  993.         long time = offset2000A % 86400l;
  994.         if (time < 0l) {
  995.             time += 86400l;
  996.         }
  997.         final int date = (int) ((offset2000A - time) / 86400l);

  998.         // extract calendar elements
  999.         final DateComponents dateComponents = new DateComponents(DateComponents.J2000_EPOCH, date);

  1000.         // extract time element, accounting for leap seconds
  1001.         final double leap = timeScale.insideLeap(this) ? timeScale.getLeap(this) : 0;
  1002.         final int minuteDuration = timeScale.minuteDuration(this);
  1003.         final TimeComponents timeComponents =
  1004.                 TimeComponents.fromSeconds((int) time, offset2000B, leap, minuteDuration);

  1005.         // build the components
  1006.         return new DateTimeComponents(dateComponents, timeComponents);

  1007.     }

  1008.     /** Split the instance into date/time components for a local time.
  1009.      *
  1010.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1011.      *
  1012.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1013.      * negative Westward UTC)
  1014.      * @return date/time components
  1015.      * @since 7.2
  1016.      * @see #getComponents(int, TimeScale)
  1017.      */
  1018.     @DefaultDataContext
  1019.     public DateTimeComponents getComponents(final int minutesFromUTC) {
  1020.         return getComponents(minutesFromUTC,
  1021.                 DataContext.getDefault().getTimeScales().getUTC());
  1022.     }

  1023.     /**
  1024.      * Split the instance into date/time components for a local time.
  1025.      *
  1026.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1027.      *                       negative Westward UTC)
  1028.      * @param utc            time scale used to compute date and time components.
  1029.      * @return date/time components
  1030.      * @since 10.1
  1031.      */
  1032.     public DateTimeComponents getComponents(final int minutesFromUTC,
  1033.                                             final TimeScale utc) {

  1034.         final DateTimeComponents utcComponents = getComponents(utc);

  1035.         // shift the date according to UTC offset, but WITHOUT touching the seconds,
  1036.         // as they may exceed 60.0 during a leap seconds introduction,
  1037.         // and we want to preserve these special cases
  1038.         final double seconds = utcComponents.getTime().getSecond();

  1039.         int minute = utcComponents.getTime().getMinute() + minutesFromUTC;
  1040.         final int hourShift;
  1041.         if (minute < 0) {
  1042.             hourShift = (minute - 59) / 60;
  1043.         } else if (minute > 59) {
  1044.             hourShift = minute / 60;
  1045.         } else {
  1046.             hourShift = 0;
  1047.         }
  1048.         minute -= 60 * hourShift;

  1049.         int hour = utcComponents.getTime().getHour() + hourShift;
  1050.         final int dayShift;
  1051.         if (hour < 0) {
  1052.             dayShift = (hour - 23) / 24;
  1053.         } else if (hour > 23) {
  1054.             dayShift = hour / 24;
  1055.         } else {
  1056.             dayShift = 0;
  1057.         }
  1058.         hour -= 24 * dayShift;

  1059.         return new DateTimeComponents(new DateComponents(utcComponents.getDate(), dayShift),
  1060.                                       new TimeComponents(hour, minute, seconds, minutesFromUTC));

  1061.     }

  1062.     /** Split the instance into date/time components for a time zone.
  1063.      *
  1064.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1065.      *
  1066.      * @param timeZone time zone
  1067.      * @return date/time components
  1068.      * @since 7.2
  1069.      * @see #getComponents(TimeZone, TimeScale)
  1070.      */
  1071.     @DefaultDataContext
  1072.     public DateTimeComponents getComponents(final TimeZone timeZone) {
  1073.         return getComponents(timeZone, DataContext.getDefault().getTimeScales().getUTC());
  1074.     }

  1075.     /**
  1076.      * Split the instance into date/time components for a time zone.
  1077.      *
  1078.      * @param timeZone time zone
  1079.      * @param utc      time scale used to computed date and time components.
  1080.      * @return date/time components
  1081.      * @since 10.1
  1082.      */
  1083.     public DateTimeComponents getComponents(final TimeZone timeZone,
  1084.                                             final TimeScale utc) {
  1085.         final AbsoluteDate javaEpoch = new AbsoluteDate(DateComponents.JAVA_EPOCH, utc);
  1086.         final long milliseconds = FastMath.round(1000 * offsetFrom(javaEpoch, utc));
  1087.         return getComponents(timeZone.getOffset(milliseconds) / 60000, utc);
  1088.     }

  1089.     /** Compare the instance with another date.
  1090.      * @param date other date to compare the instance to
  1091.      * @return a negative integer, zero, or a positive integer as this date
  1092.      * is before, simultaneous, or after the specified date.
  1093.      */
  1094.     public int compareTo(final AbsoluteDate date) {
  1095.         final double duration = durationFrom(date);
  1096.         if (!Double.isNaN(duration)) {
  1097.             return Double.compare(duration, 0.0);
  1098.         }
  1099.         // both dates are infinity or one is NaN or both are NaN
  1100.         return Double.compare(offset, date.offset);
  1101.     }

  1102.     /** {@inheritDoc} */
  1103.     public AbsoluteDate getDate() {
  1104.         return this;
  1105.     }

  1106.     /** Check if the instance represents the same time as another instance.
  1107.      * @param date other date
  1108.      * @return true if the instance and the other date refer to the same instant
  1109.      */
  1110.     public boolean equals(final Object date) {

  1111.         if (date == this) {
  1112.             // first fast check
  1113.             return true;
  1114.         }

  1115.         if ((date != null) && (date instanceof AbsoluteDate)) {
  1116.             return durationFrom((AbsoluteDate) date) == 0;
  1117.         }

  1118.         return false;

  1119.     }

  1120.     /** Check if the instance represents the same time as another.
  1121.      * @param other the instant to compare this date to
  1122.      * @return true if the instance and the argument refer to the same instant
  1123.      * @see #isCloseTo(TimeStamped, double)
  1124.      * @since 10.1
  1125.      */
  1126.     public boolean isEqualTo(final TimeStamped other) {
  1127.         return this.equals(other.getDate());
  1128.     }

  1129.     /** Check if the instance time is close to another.
  1130.      * @param other the instant to compare this date to
  1131.      * @param tolerance the separation, in seconds, under which the two instants will be considered close to each other
  1132.      * @return true if the duration between the instance and the argument is strictly below the tolerance
  1133.      * @see #isEqualTo(TimeStamped)
  1134.      * @since 10.1
  1135.      */
  1136.     public boolean isCloseTo(final TimeStamped other, final double tolerance) {
  1137.         return FastMath.abs(this.durationFrom(other.getDate())) < tolerance;
  1138.     }

  1139.     /** Check if the instance represents a time that is strictly before another.
  1140.      * @param other the instant to compare this date to
  1141.      * @return true if the instance is strictly before the argument when ordering chronologically
  1142.      * @see #isBeforeOrEqualTo(TimeStamped)
  1143.      * @since 10.1
  1144.      */
  1145.     public boolean isBefore(final TimeStamped other) {
  1146.         return this.compareTo(other.getDate()) < 0;
  1147.     }

  1148.     /** Check if the instance represents a time that is strictly after another.
  1149.      * @param other the instant to compare this date to
  1150.      * @return true if the instance is strictly after the argument when ordering chronologically
  1151.      * @see #isAfterOrEqualTo(TimeStamped)
  1152.      * @since 10.1
  1153.      */
  1154.     public boolean isAfter(final TimeStamped other) {
  1155.         return this.compareTo(other.getDate()) > 0;
  1156.     }

  1157.     /** Check if the instance represents a time that is before or equal to another.
  1158.      * @param other the instant to compare this date to
  1159.      * @return true if the instance is before (or equal to) the argument when ordering chronologically
  1160.      * @see #isBefore(TimeStamped)
  1161.      * @since 10.1
  1162.      */
  1163.     public boolean isBeforeOrEqualTo(final TimeStamped other) {
  1164.         return this.isEqualTo(other) || this.isBefore(other);
  1165.     }

  1166.     /** Check if the instance represents a time that is after or equal to another.
  1167.      * @param other the instant to compare this date to
  1168.      * @return true if the instance is after (or equal to) the argument when ordering chronologically
  1169.      * @see #isAfterOrEqualTo(TimeStamped)
  1170.      * @since 10.1
  1171.      */
  1172.     public boolean isAfterOrEqualTo(final TimeStamped other) {
  1173.         return this.isEqualTo(other) || this.isAfter(other);
  1174.     }

  1175.     /** Check if the instance represents a time that is strictly between two others representing
  1176.      * the boundaries of a time span. The two boundaries can be provided in any order: in other words,
  1177.      * whether <code>boundary</code> represents a time that is before or after <code>otherBoundary</code> will
  1178.      * not change the result of this method.
  1179.      * @param boundary one end of the time span
  1180.      * @param otherBoundary the other end of the time span
  1181.      * @return true if the instance is strictly between the two arguments when ordering chronologically
  1182.      * @see #isBetweenOrEqualTo(TimeStamped, TimeStamped)
  1183.      * @since 10.1
  1184.      */
  1185.     public boolean isBetween(final TimeStamped boundary, final TimeStamped otherBoundary) {
  1186.         final TimeStamped beginning;
  1187.         final TimeStamped end;
  1188.         if (boundary.getDate().isBefore(otherBoundary)) {
  1189.             beginning = boundary;
  1190.             end = otherBoundary;
  1191.         } else {
  1192.             beginning = otherBoundary;
  1193.             end = boundary;
  1194.         }
  1195.         return this.isAfter(beginning) && this.isBefore(end);
  1196.     }

  1197.     /** Check if the instance represents a time that is between two others representing
  1198.      * the boundaries of a time span, or equal to one of them. The two boundaries can be provided in any order:
  1199.      * in other words, whether <code>boundary</code> represents a time that is before or after
  1200.      * <code>otherBoundary</code> will not change the result of this method.
  1201.      * @param boundary one end of the time span
  1202.      * @param otherBoundary the other end of the time span
  1203.      * @return true if the instance is between the two arguments (or equal to at least one of them)
  1204.      * when ordering chronologically
  1205.      * @see #isBetween(TimeStamped, TimeStamped)
  1206.      * @since 10.1
  1207.      */
  1208.     public boolean isBetweenOrEqualTo(final TimeStamped boundary, final TimeStamped otherBoundary) {
  1209.         return this.isEqualTo(boundary) || this.isEqualTo(otherBoundary) || this.isBetween(boundary, otherBoundary);
  1210.     }

  1211.     /** Get a hashcode for this date.
  1212.      * @return hashcode
  1213.      */
  1214.     public int hashCode() {
  1215.         final long l = Double.doubleToLongBits(durationFrom(ARBITRARY_EPOCH));
  1216.         return (int) (l ^ (l >>> 32));
  1217.     }

  1218.     /** Get a String representation of the instant location in UTC time scale.
  1219.      *
  1220.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1221.      *
  1222.      * @return a string representation of the instance,
  1223.      * in ISO-8601 format with milliseconds accuracy
  1224.      * @see #toString(TimeScale)
  1225.      */
  1226.     @DefaultDataContext
  1227.     public String toString() {
  1228.         return toString(DataContext.getDefault().getTimeScales().getUTC());
  1229.     }

  1230.     /** Get a String representation of the instant location.
  1231.      * @param timeScale time scale to use
  1232.      * @return a string representation of the instance,
  1233.      * in ISO-8601 format with milliseconds accuracy
  1234.      */
  1235.     public String toString(final TimeScale timeScale) {
  1236.         return getComponents(timeScale).toString(timeScale.minuteDuration(this));
  1237.     }

  1238.     /** Get a String representation of the instant location for a local time.
  1239.      *
  1240.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1241.      *
  1242.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1243.      * negative Westward UTC).
  1244.      * @return string representation of the instance,
  1245.      * in ISO-8601 format with milliseconds accuracy
  1246.      * @since 7.2
  1247.      * @see #toString(int, TimeScale)
  1248.      */
  1249.     @DefaultDataContext
  1250.     public String toString(final int minutesFromUTC) {
  1251.         return toString(minutesFromUTC,
  1252.                 DataContext.getDefault().getTimeScales().getUTC());
  1253.     }

  1254.     /**
  1255.      * Get a String representation of the instant location for a local time.
  1256.      *
  1257.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1258.      *                       negative Westward UTC).
  1259.      * @param utc            time scale used to compute date and time components.
  1260.      * @return string representation of the instance, in ISO-8601 format with milliseconds
  1261.      * accuracy
  1262.      * @since 10.1
  1263.      */
  1264.     public String toString(final int minutesFromUTC, final TimeScale utc) {
  1265.         final int minuteDuration = utc.minuteDuration(this);
  1266.         return getComponents(minutesFromUTC, utc).toString(minuteDuration);
  1267.     }

  1268.     /** Get a String representation of the instant location for a time zone.
  1269.      *
  1270.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1271.      *
  1272.      * @param timeZone time zone
  1273.      * @return string representation of the instance,
  1274.      * in ISO-8601 format with milliseconds accuracy
  1275.      * @since 7.2
  1276.      * @see #toString(TimeZone, TimeScale)
  1277.      */
  1278.     @DefaultDataContext
  1279.     public String toString(final TimeZone timeZone) {
  1280.         return toString(timeZone, DataContext.getDefault().getTimeScales().getUTC());
  1281.     }

  1282.     /**
  1283.      * Get a String representation of the instant location for a time zone.
  1284.      *
  1285.      * @param timeZone time zone
  1286.      * @param utc      time scale used to compute date and time components.
  1287.      * @return string representation of the instance, in ISO-8601 format with milliseconds
  1288.      * accuracy
  1289.      * @since 10.1
  1290.      */
  1291.     public String toString(final TimeZone timeZone, final TimeScale utc) {
  1292.         final int minuteDuration = utc.minuteDuration(this);
  1293.         return getComponents(timeZone, utc).toString(minuteDuration);
  1294.     }

  1295.     /**
  1296.      * Represent the given date as a string according to the format in RFC 3339. RFC3339
  1297.      * is a restricted subset of ISO 8601 with a well defined grammar.
  1298.      *
  1299.      * <p>This method is different than {@link AbsoluteDate#toString(TimeScale)} in that
  1300.      * it includes a {@code "Z"} at the end to indicate the time zone and enough precision
  1301.      * to represent the point in time without rounding up to the next minute.
  1302.      *
  1303.      * <p>RFC3339 is unable to represent BC years, years of 10000 or more, time zone
  1304.      * offsets of 100 hours or more, or NaN. In these cases the value returned from this
  1305.      * method will not be valid RFC3339 format.
  1306.      *
  1307.      * @param utc time scale.
  1308.      * @return RFC 3339 format string.
  1309.      * @see <a href="https://tools.ietf.org/html/rfc3339#page-8">RFC 3339</a>
  1310.      * @see DateTimeComponents#toStringRfc3339()
  1311.      * @see #toString(TimeScale)
  1312.      * @see #getComponents(TimeScale)
  1313.      */
  1314.     public String toStringRfc3339(final TimeScale utc) {
  1315.         return this.getComponents(utc).toStringRfc3339();
  1316.     }

  1317. }