AbsoluteDate.java

  1. /* Copyright 2002-2022 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.hipparchus.util.MathUtils;
  23. import org.hipparchus.util.MathUtils.SumAndResidual;
  24. import org.orekit.annotation.DefaultDataContext;
  25. import org.orekit.data.DataContext;
  26. import org.orekit.errors.OrekitException;
  27. import org.orekit.errors.OrekitIllegalArgumentException;
  28. import org.orekit.errors.OrekitMessages;
  29. import org.orekit.utils.Constants;


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  234.     /** Serializable UID. */
  235.     private static final long serialVersionUID = 617061803741806846L;

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

  239.     /** Offset from the reference epoch in seconds. */
  240.     private final double offset;

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

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

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

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

  283.         final double seconds  = time.getSecond();
  284.         final double tsOffset = timeScale.offsetToTAI(date, time);

  285.         // Use 2Sum for high precision.
  286.         final SumAndResidual sumAndResidual = MathUtils.twoSum(seconds, tsOffset);
  287.         final long dl = (long) FastMath.floor(sumAndResidual.getSum());
  288.         final double regularOffset = (sumAndResidual.getSum() - dl) + sumAndResidual.getResidual();

  289.         if (regularOffset >= 0) {
  290.             // regular case, the offset is between 0.0 and 1.0
  291.             offset = regularOffset;
  292.             epoch  = 60l * ((date.getJ2000Day() * 24l + time.getHour()) * 60l +
  293.                             time.getMinute() - time.getMinutesFromUTC() - 720l) + dl;
  294.         } else {
  295.             // very rare case, the offset is just before a whole second
  296.             // we will loose some bits of accuracy when adding 1 second
  297.             // but this will ensure the offset remains in the [0.0; 1.0] interval
  298.             offset = 1.0 + regularOffset;
  299.             epoch  = 60l * ((date.getJ2000Day() * 24l + time.getHour()) * 60l +
  300.                             time.getMinute() - time.getMinutesFromUTC() - 720l) + dl - 1;
  301.         }

  302.     }

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

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

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

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

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

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

  382.     /** Build an instance from an elapsed duration since to another instant.
  383.      * <p>It is important to note that the elapsed duration is <em>not</em>
  384.      * the difference between two readings on a time scale. As an example,
  385.      * the duration between the two instants leading to the readings
  386.      * 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the {@link UTCScale UTC}
  387.      * time scale is <em>not</em> 1 second, but a stop watch would have measured
  388.      * an elapsed duration of 2 seconds between these two instances because a leap
  389.      * second was introduced at the end of 2005 in this time scale.</p>
  390.      * <p>This constructor is the reverse of the {@link #durationFrom(AbsoluteDate)}
  391.      * method.</p>
  392.      * @param since start instant of the measured duration
  393.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  394.      * instant, as measured in a regular time scale
  395.      * @see #durationFrom(AbsoluteDate)
  396.      */
  397.     public AbsoluteDate(final AbsoluteDate since, final double elapsedDuration) {
  398.         // Use 2Sum for high precision.
  399.         final SumAndResidual sumAndResidual = MathUtils.twoSum(since.offset, elapsedDuration);
  400.         if (Double.isInfinite(sumAndResidual.getSum())) {
  401.             offset = sumAndResidual.getSum();
  402.             epoch  = (sumAndResidual.getSum() < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
  403.         } else {
  404.             final long dl = (long) FastMath.floor(sumAndResidual.getSum());
  405.             final double regularOffset = (sumAndResidual.getSum() - dl) + sumAndResidual.getResidual();
  406.             if (regularOffset >= 0) {
  407.                 // regular case, the offset is between 0.0 and 1.0
  408.                 offset = regularOffset;
  409.                 epoch  = since.epoch + dl;
  410.             } else {
  411.                 // very rare case, the offset is just before a whole second
  412.                 // we will loose some bits of accuracy when adding 1 second
  413.                 // but this will ensure the offset remains in the [0.0; 1.0] interval
  414.                 offset = 1.0 + regularOffset;
  415.                 epoch  = since.epoch + dl - 1;
  416.             }
  417.         }
  418.     }

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

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

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

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

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

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

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

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

  576.         // time field lengths
  577.         int coarseTimeLength = 1 + ((preambleField1 & 0x0C) >>> 2);
  578.         int fineTimeLength   = preambleField1 & 0x03;

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

  584.         if (timeField.length != coarseTimeLength + fineTimeLength) {
  585.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  586.                                       timeField.length, coarseTimeLength + fineTimeLength);
  587.         }

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

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

  597.     }

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

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

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

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

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


  669.         int i   = 0;
  670.         int day = 0;
  671.         while (i < daySegmentLength) {
  672.             day = day * 256 + toUnsigned(timeField[i++]);
  673.         }

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

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

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

  689.     }

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

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

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

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

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

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

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

  763.     }

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

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

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

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

  820.         // create the date
  821.         return new AbsoluteDate(dc, tc, timeScale);

  822.     }


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

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

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

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

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

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

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

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

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

  974.         // Compute offset from 2000-01-01T00:00:00 in specified time scale.
  975.         // Use 2Sum for high precision.
  976.         final double taiOffset = timeScale.offsetFromTAI(this);
  977.         final SumAndResidual sumAndResidual = MathUtils.twoSum(offset, taiOffset);

  978.         // split date and time
  979.         final long   carry = (long) FastMath.floor(sumAndResidual.getSum());
  980.         double offset2000B = (sumAndResidual.getSum() - carry) + sumAndResidual.getResidual();
  981.         long   offset2000A = epoch + carry + 43200l;
  982.         if (offset2000B < 0) {
  983.             offset2000A -= 1;
  984.             offset2000B += 1;
  985.         }
  986.         long time = offset2000A % 86400l;
  987.         if (time < 0l) {
  988.             time += 86400l;
  989.         }
  990.         final int date = (int) ((offset2000A - time) / 86400l);

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

  993.         // extract time element, accounting for leap seconds
  994.         final double leap = timeScale.insideLeap(this) ? timeScale.getLeap(this) : 0;
  995.         final int minuteDuration = timeScale.minuteDuration(this);
  996.         final TimeComponents timeComponents =
  997.                 TimeComponents.fromSeconds((int) time, offset2000B, leap, minuteDuration);

  998.         // build the components
  999.         return new DateTimeComponents(dateComponents, timeComponents);

  1000.     }

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

  1016.     /**
  1017.      * Split the instance into date/time components for a local time.
  1018.      *
  1019.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1020.      *                       negative Westward UTC)
  1021.      * @param utc            time scale used to compute date and time components.
  1022.      * @return date/time components
  1023.      * @since 10.1
  1024.      */
  1025.     public DateTimeComponents getComponents(final int minutesFromUTC,
  1026.                                             final TimeScale utc) {

  1027.         final DateTimeComponents utcComponents = getComponents(utc);

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

  1032.         int minute = utcComponents.getTime().getMinute() + minutesFromUTC;
  1033.         final int hourShift;
  1034.         if (minute < 0) {
  1035.             hourShift = (minute - 59) / 60;
  1036.         } else if (minute > 59) {
  1037.             hourShift = minute / 60;
  1038.         } else {
  1039.             hourShift = 0;
  1040.         }
  1041.         minute -= 60 * hourShift;

  1042.         int hour = utcComponents.getTime().getHour() + hourShift;
  1043.         final int dayShift;
  1044.         if (hour < 0) {
  1045.             dayShift = (hour - 23) / 24;
  1046.         } else if (hour > 23) {
  1047.             dayShift = hour / 24;
  1048.         } else {
  1049.             dayShift = 0;
  1050.         }
  1051.         hour -= 24 * dayShift;

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

  1054.     }

  1055.     /** Split the instance into date/time components for a time zone.
  1056.      *
  1057.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1058.      *
  1059.      * @param timeZone time zone
  1060.      * @return date/time components
  1061.      * @since 7.2
  1062.      * @see #getComponents(TimeZone, TimeScale)
  1063.      */
  1064.     @DefaultDataContext
  1065.     public DateTimeComponents getComponents(final TimeZone timeZone) {
  1066.         return getComponents(timeZone, DataContext.getDefault().getTimeScales().getUTC());
  1067.     }

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

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

  1095.     /** {@inheritDoc} */
  1096.     public AbsoluteDate getDate() {
  1097.         return this;
  1098.     }

  1099.     /** Check if the instance represents the same time as another instance.
  1100.      * @param date other date
  1101.      * @return true if the instance and the other date refer to the same instant
  1102.      */
  1103.     public boolean equals(final Object date) {

  1104.         if (date == this) {
  1105.             // first fast check
  1106.             return true;
  1107.         }

  1108.         if (date instanceof AbsoluteDate) {

  1109.             // Improve robustness against positive/negative infinity dates
  1110.             if ( this.offset == Double.NEGATIVE_INFINITY && ((AbsoluteDate) date).offset == Double.NEGATIVE_INFINITY ||
  1111.                     this.offset == Double.POSITIVE_INFINITY && ((AbsoluteDate) date).offset == Double.POSITIVE_INFINITY ) {
  1112.                 return true;
  1113.             } else {
  1114.                 return durationFrom((AbsoluteDate) date) == 0;
  1115.             }
  1116.         }

  1117.         return false;
  1118.     }

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

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

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

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

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

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

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

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

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

  1217.     /**
  1218.      * Get a String representation of the instant location with up to 16 digits of
  1219.      * precision for the seconds value.
  1220.      *
  1221.      * <p> Since this method is used in exception messages and error handling every
  1222.      * effort is made to return some representation of the instant. If UTC is available
  1223.      * from the default data context then it is used to format the string in UTC. If not
  1224.      * then TAI is used. Finally if the prior attempts fail this method falls back to
  1225.      * converting this class's internal representation to a string.
  1226.      *
  1227.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1228.      *
  1229.      * @return a string representation of the instance, in ISO-8601 format if UTC is
  1230.      * available from the default data context.
  1231.      * @see #toString(TimeScale)
  1232.      * @see #toStringRfc3339(TimeScale)
  1233.      * @see DateTimeComponents#toString(int, int)
  1234.      */
  1235.     @DefaultDataContext
  1236.     public String toString() {
  1237.         // CHECKSTYLE: stop IllegalCatch check
  1238.         try {
  1239.             // try to use UTC first at that is likely most familiar to the user.
  1240.             return toString(DataContext.getDefault().getTimeScales().getUTC()) + "Z";
  1241.         } catch (RuntimeException e1) {
  1242.             // catch OrekitException, OrekitIllegalStateException, etc.
  1243.             try {
  1244.                 // UTC failed, try to use TAI
  1245.                 return toString(new TAIScale()) + " TAI";
  1246.             } catch (RuntimeException e2) {
  1247.                 // catch OrekitException, OrekitIllegalStateException, etc.
  1248.                 // Likely failed to convert to ymdhms.
  1249.                 // Give user some indication of what time it is.
  1250.                 try {
  1251.                     return "(" + this.epoch + " + " + this.offset + ") seconds past epoch";
  1252.                 } catch (RuntimeException e3) {
  1253.                     // give up and throw an exception
  1254.                     e2.addSuppressed(e3);
  1255.                     e1.addSuppressed(e2);
  1256.                     throw e1;
  1257.                 }
  1258.             }
  1259.         }
  1260.         // CHECKSTYLE: resume IllegalCatch check
  1261.     }

  1262.     /**
  1263.      * Get a String representation of the instant location in ISO-8601 format without the
  1264.      * UTC offset and with up to 16 digits of precision for the seconds value.
  1265.      *
  1266.      * @param timeScale time scale to use
  1267.      * @return a string representation of the instance.
  1268.      * @see #toStringRfc3339(TimeScale)
  1269.      * @see DateTimeComponents#toString(int, int)
  1270.      */
  1271.     public String toString(final TimeScale timeScale) {
  1272.         return getComponents(timeScale).toStringWithoutUtcOffset();
  1273.     }

  1274.     /** Get a String representation of the instant location for a local time.
  1275.      *
  1276.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1277.      *
  1278.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1279.      * negative Westward UTC).
  1280.      * @return string representation of the instance,
  1281.      * in ISO-8601 format with milliseconds accuracy
  1282.      * @since 7.2
  1283.      * @see #toString(int, TimeScale)
  1284.      */
  1285.     @DefaultDataContext
  1286.     public String toString(final int minutesFromUTC) {
  1287.         return toString(minutesFromUTC,
  1288.                 DataContext.getDefault().getTimeScales().getUTC());
  1289.     }

  1290.     /**
  1291.      * Get a String representation of the instant location for a local time.
  1292.      *
  1293.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1294.      *                       negative Westward UTC).
  1295.      * @param utc            time scale used to compute date and time components.
  1296.      * @return string representation of the instance, in ISO-8601 format with milliseconds
  1297.      * accuracy
  1298.      * @since 10.1
  1299.      * @see #getComponents(int, TimeScale)
  1300.      * @see DateTimeComponents#toString(int, int)
  1301.      */
  1302.     public String toString(final int minutesFromUTC, final TimeScale utc) {
  1303.         final int minuteDuration = utc.minuteDuration(this);
  1304.         return getComponents(minutesFromUTC, utc).toString(minuteDuration);
  1305.     }

  1306.     /** Get a String representation of the instant location for a time zone.
  1307.      *
  1308.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1309.      *
  1310.      * @param timeZone time zone
  1311.      * @return string representation of the instance,
  1312.      * in ISO-8601 format with milliseconds accuracy
  1313.      * @since 7.2
  1314.      * @see #toString(TimeZone, TimeScale)
  1315.      */
  1316.     @DefaultDataContext
  1317.     public String toString(final TimeZone timeZone) {
  1318.         return toString(timeZone, DataContext.getDefault().getTimeScales().getUTC());
  1319.     }

  1320.     /**
  1321.      * Get a String representation of the instant location for a time zone.
  1322.      *
  1323.      * @param timeZone time zone
  1324.      * @param utc      time scale used to compute date and time components.
  1325.      * @return string representation of the instance, in ISO-8601 format with milliseconds
  1326.      * accuracy
  1327.      * @since 10.1
  1328.      * @see #getComponents(TimeZone, TimeScale)
  1329.      * @see DateTimeComponents#toString(int, int)
  1330.      */
  1331.     public String toString(final TimeZone timeZone, final TimeScale utc) {
  1332.         final int minuteDuration = utc.minuteDuration(this);
  1333.         return getComponents(timeZone, utc).toString(minuteDuration);
  1334.     }

  1335.     /**
  1336.      * Represent the given date as a string according to the format in RFC 3339. RFC3339
  1337.      * is a restricted subset of ISO 8601 with a well defined grammar. Enough digits are
  1338.      * included in the seconds value to avoid rounding up to the next minute.
  1339.      *
  1340.      * <p>This method is different than {@link AbsoluteDate#toString(TimeScale)} in that
  1341.      * it includes a {@code "Z"} at the end to indicate the time zone and enough precision
  1342.      * to represent the point in time without rounding up to the next minute.
  1343.      *
  1344.      * <p>RFC3339 is unable to represent BC years, years of 10000 or more, time zone
  1345.      * offsets of 100 hours or more, or NaN. In these cases the value returned from this
  1346.      * method will not be valid RFC3339 format.
  1347.      *
  1348.      * @param utc time scale.
  1349.      * @return RFC 3339 format string.
  1350.      * @see <a href="https://tools.ietf.org/html/rfc3339#page-8">RFC 3339</a>
  1351.      * @see DateTimeComponents#toStringRfc3339()
  1352.      * @see #toString(TimeScale)
  1353.      * @see #getComponents(TimeScale)
  1354.      */
  1355.     public String toStringRfc3339(final TimeScale utc) {
  1356.         return this.getComponents(utc).toStringRfc3339();
  1357.     }

  1358.     /**
  1359.      * Return a string representation of this date-time, rounded to the given precision.
  1360.      *
  1361.      * <p>The format used is ISO8601 without the UTC offset.</p>
  1362.      *
  1363.      * <p>Calling {@code toStringWithoutUtcOffset(DataContext.getDefault().getTimeScales().getUTC(),
  1364.      * 3)} will emulate the behavior of {@link #toString()} in Orekit 10 and earlier. Note
  1365.      * this method is more accurate as it correctly handles rounding during leap seconds.
  1366.      *
  1367.      * @param timeScale      to use to compute components.
  1368.      * @param fractionDigits the number of digits to include after the decimal point in
  1369.      *                       the string representation of the seconds. The date and time
  1370.      *                       is first rounded as necessary. {@code fractionDigits} must be
  1371.      *                       greater than or equal to {@code 0}.
  1372.      * @return string representation of this date, time, and UTC offset
  1373.      * @see #toString(TimeScale)
  1374.      * @see #toStringRfc3339(TimeScale)
  1375.      * @see DateTimeComponents#toString(int, int)
  1376.      * @see DateTimeComponents#toStringWithoutUtcOffset(int, int)
  1377.      * @since 11.1
  1378.      */
  1379.     public String toStringWithoutUtcOffset(final TimeScale timeScale,
  1380.                                            final int fractionDigits) {
  1381.         return this.getComponents(timeScale)
  1382.                 .toStringWithoutUtcOffset(timeScale.minuteDuration(this), fractionDigits);
  1383.     }

  1384. }