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.         offset = (sumAndResidual.getSum() - dl) + sumAndResidual.getResidual();
  289.         epoch  = 60l * ((date.getJ2000Day() * 24l + time.getHour()) * 60l +
  290.                         time.getMinute() - time.getMinutesFromUTC() - 720l) + dl;

  291.     }

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

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

  324.     /** Build an instance from a location in a {@link TimeScale time scale}.
  325.      * <p>The hour is set to 00:00:00.000.</p>
  326.      * @param date date location in the time scale
  327.      * @param timeScale time scale
  328.      * @exception IllegalArgumentException if inconsistent arguments
  329.      * are given (parameters out of range)
  330.      */
  331.     public AbsoluteDate(final DateComponents date, final TimeScale timeScale)
  332.         throws IllegalArgumentException {
  333.         this(date, TimeComponents.H00, 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 year year number (may be 0 or negative for BC years)
  338.      * @param month month number from 1 to 12
  339.      * @param day day number from 1 to 31
  340.      * @param timeScale time scale
  341.      * @exception IllegalArgumentException if inconsistent arguments
  342.      * are given (parameters out of range)
  343.      */
  344.     public AbsoluteDate(final int year, final int month, final int day,
  345.                         final TimeScale timeScale) throws IllegalArgumentException {
  346.         this(new DateComponents(year, month, day), TimeComponents.H00, timeScale);
  347.     }

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

  361.     /** Build an instance from a location in a {@link TimeScale time scale}.
  362.      * @param location location in the time scale
  363.      * @param timeScale time scale
  364.      */
  365.     public AbsoluteDate(final Date location, final TimeScale timeScale) {
  366.         this(new DateComponents(DateComponents.JAVA_EPOCH,
  367.                                 (int) (location.getTime() / 86400000l)),
  368.                                  millisToTimeComponents((int) (location.getTime() % 86400000l)),
  369.              timeScale);
  370.     }

  371.     /** Build an instance from an elapsed duration since to another instant.
  372.      * <p>It is important to note that the elapsed duration is <em>not</em>
  373.      * the difference between two readings on a time scale. As an example,
  374.      * the duration between the two instants leading to the readings
  375.      * 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the {@link UTCScale UTC}
  376.      * time scale is <em>not</em> 1 second, but a stop watch would have measured
  377.      * an elapsed duration of 2 seconds between these two instances because a leap
  378.      * second was introduced at the end of 2005 in this time scale.</p>
  379.      * <p>This constructor is the reverse of the {@link #durationFrom(AbsoluteDate)}
  380.      * method.</p>
  381.      * @param since start instant of the measured duration
  382.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  383.      * instant, as measured in a regular time scale
  384.      * @see #durationFrom(AbsoluteDate)
  385.      */
  386.     public AbsoluteDate(final AbsoluteDate since, final double elapsedDuration) {
  387.         // Use 2Sum for high precision.
  388.         final SumAndResidual sumAndResidual = MathUtils.twoSum(since.offset, elapsedDuration);
  389.         if (Double.isInfinite(sumAndResidual.getSum())) {
  390.             offset = sumAndResidual.getSum();
  391.             epoch  = (sumAndResidual.getSum() < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
  392.         } else {
  393.             final long dl = (long) FastMath.floor(sumAndResidual.getSum());
  394.             offset = (sumAndResidual.getSum() - dl) + sumAndResidual.getResidual();
  395.             epoch  = since.epoch + dl;
  396.         }
  397.     }

  398.     /** Build an instance from an apparent clock offset with respect to another
  399.      * instant <em>in the perspective of a specific {@link TimeScale time scale}</em>.
  400.      * <p>It is important to note that the apparent clock offset <em>is</em> the
  401.      * difference between two readings on a time scale and <em>not</em> an elapsed
  402.      * duration. As an example, the apparent clock offset between the two instants
  403.      * leading to the readings 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the
  404.      * {@link UTCScale UTC} time scale is 1 second, but the elapsed duration is 2
  405.      * seconds because a leap second has been introduced at the end of 2005 in this
  406.      * time scale.</p>
  407.      * <p>This constructor is the reverse of the {@link #offsetFrom(AbsoluteDate,
  408.      * TimeScale)} method.</p>
  409.      * @param reference reference instant
  410.      * @param apparentOffset apparent clock offset from the reference instant
  411.      * (difference between two readings in the specified time scale)
  412.      * @param timeScale time scale with respect to which the offset is defined
  413.      * @see #offsetFrom(AbsoluteDate, TimeScale)
  414.      */
  415.     public AbsoluteDate(final AbsoluteDate reference, final double apparentOffset,
  416.                         final TimeScale timeScale) {
  417.         this(new DateTimeComponents(reference.getComponents(timeScale), apparentOffset),
  418.              timeScale);
  419.     }

  420.     /** Build a date from its internal components.
  421.      * <p>
  422.      * This method is reserved for internal used (for example by {@link FieldAbsoluteDate}).
  423.      * </p>
  424.      * @param epoch reference epoch in seconds from 2000-01-01T12:00:00 TAI.
  425.      * (beware, it is not {@link #J2000_EPOCH} since it is in TAI and not in TT)
  426.      * @param offset offset from the reference epoch in seconds (must be
  427.      * between 0.0 included and 1.0 excluded)
  428.      * @since 9.0
  429.      */
  430.     AbsoluteDate(final long epoch, final double offset) {
  431.         this.epoch  = epoch;
  432.         this.offset = offset;
  433.     }

  434.     /** Extract time components from a number of milliseconds within the day.
  435.      * @param millisInDay number of milliseconds within the day
  436.      * @return time components
  437.      */
  438.     private static TimeComponents millisToTimeComponents(final int millisInDay) {
  439.         return new TimeComponents(millisInDay / 1000, 0.001 * (millisInDay % 1000));
  440.     }

  441.     /** Get the reference epoch in seconds from 2000-01-01T12:00:00 TAI.
  442.      * <p>
  443.      * This method is reserved for internal used (for example by {@link FieldAbsoluteDate}).
  444.      * </p>
  445.      * <p>
  446.      * Beware, it is not {@link #J2000_EPOCH} since it is in TAI and not in TT.
  447.      * </p>
  448.      * @return reference epoch in seconds from 2000-01-01T12:00:00 TAI
  449.      * @since 9.0
  450.      */
  451.     long getEpoch() {
  452.         return epoch;
  453.     }

  454.     /** Get the offset from the reference epoch in seconds.
  455.      * <p>
  456.      * This method is reserved for internal used (for example by {@link FieldAbsoluteDate}).
  457.      * </p>
  458.      * @return offset from the reference epoch in seconds
  459.      * @since 9.0
  460.      */
  461.     double getOffset() {
  462.         return offset;
  463.     }

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

  501.     /**
  502.      * Build an instance from a CCSDS Unsegmented Time Code (CUC).
  503.      * <p>
  504.      * CCSDS Unsegmented Time Code is defined in the blue book: CCSDS Time Code Format
  505.      * (CCSDS 301.0-B-4) published in November 2010
  506.      * </p>
  507.      * <p>
  508.      * If the date to be parsed is formatted using version 3 of the standard (CCSDS
  509.      * 301.0-B-3 published in 2002) or if the extension of the preamble field introduced
  510.      * in version 4 of the standard is not used, then the {@code preambleField2} parameter
  511.      * can be set to 0.
  512.      * </p>
  513.      *
  514.      * @param preambleField1     first byte of the field specifying the format, often not
  515.      *                           transmitted in data interfaces, as it is constant for a
  516.      *                           given data interface
  517.      * @param preambleField2     second byte of the field specifying the format (added in
  518.      *                           revision 4 of the CCSDS standard in 2010), often not
  519.      *                           transmitted in data interfaces, as it is constant for a
  520.      *                           given data interface (value ignored if presence not
  521.      *                           signaled in {@code preambleField1})
  522.      * @param timeField          byte array containing the time code
  523.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field specifies
  524.      *                           the {@link #CCSDS_EPOCH CCSDS reference epoch} is used
  525.      *                           (and hence may be null in this case)
  526.      * @param ccsdsEpoch         reference epoch, ignored if the preamble field specifies
  527.      *                           the agency epoch is used.
  528.      * @return an instance corresponding to the specified date
  529.      * @since 10.1
  530.      */
  531.     public static AbsoluteDate parseCCSDSUnsegmentedTimeCode(
  532.             final byte preambleField1,
  533.             final byte preambleField2,
  534.             final byte[] timeField,
  535.             final AbsoluteDate agencyDefinedEpoch,
  536.             final AbsoluteDate ccsdsEpoch) {

  537.         // time code identification and reference epoch
  538.         final AbsoluteDate epoch;
  539.         switch (preambleField1 & 0x70) {
  540.             case 0x10:
  541.                 // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  542.                 epoch = ccsdsEpoch;
  543.                 break;
  544.             case 0x20:
  545.                 // the reference epoch is agency defined
  546.                 if (agencyDefinedEpoch == null) {
  547.                     throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  548.                 }
  549.                 epoch = agencyDefinedEpoch;
  550.                 break;
  551.             default :
  552.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  553.                                           formatByte(preambleField1));
  554.         }

  555.         // time field lengths
  556.         int coarseTimeLength = 1 + ((preambleField1 & 0x0C) >>> 2);
  557.         int fineTimeLength   = preambleField1 & 0x03;

  558.         if ((preambleField1 & 0x80) != 0x0) {
  559.             // there is an additional octet in preamble field
  560.             coarseTimeLength += (preambleField2 & 0x60) >>> 5;
  561.             fineTimeLength   += (preambleField2 & 0x1C) >>> 2;
  562.         }

  563.         if (timeField.length != coarseTimeLength + fineTimeLength) {
  564.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  565.                                       timeField.length, coarseTimeLength + fineTimeLength);
  566.         }

  567.         double seconds = 0;
  568.         for (int i = 0; i < coarseTimeLength; ++i) {
  569.             seconds = seconds * 256 + toUnsigned(timeField[i]);
  570.         }
  571.         double subseconds = 0;
  572.         for (int i = timeField.length - 1; i >= coarseTimeLength; --i) {
  573.             subseconds = (subseconds + toUnsigned(timeField[i])) / 256;
  574.         }

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

  576.     }

  577.     /** Build an instance from a CCSDS Day Segmented Time Code (CDS).
  578.      * <p>
  579.      * CCSDS Day Segmented Time Code is defined in the blue book:
  580.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  581.      * </p>
  582.      *
  583.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  584.      *
  585.      * @param preambleField field specifying the format, often not transmitted in
  586.      * data interfaces, as it is constant for a given data interface
  587.      * @param timeField byte array containing the time code
  588.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  589.      * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
  590.      * may be null in this case)
  591.      * @return an instance corresponding to the specified date
  592.      * @see #parseCCSDSDaySegmentedTimeCode(byte, byte[], DateComponents, TimeScale)
  593.      */
  594.     @DefaultDataContext
  595.     public static AbsoluteDate parseCCSDSDaySegmentedTimeCode(final byte preambleField, final byte[] timeField,
  596.                                                               final DateComponents agencyDefinedEpoch) {
  597.         return parseCCSDSDaySegmentedTimeCode(preambleField, timeField,
  598.                 agencyDefinedEpoch, DataContext.getDefault().getTimeScales().getUTC());
  599.     }

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

  620.         // time code identification
  621.         if ((preambleField & 0xF0) != 0x40) {
  622.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  623.                                       formatByte(preambleField));
  624.         }

  625.         // reference epoch
  626.         final DateComponents epoch;
  627.         if ((preambleField & 0x08) == 0x00) {
  628.             // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  629.             epoch = DateComponents.CCSDS_EPOCH;
  630.         } else {
  631.             // the reference epoch is agency defined
  632.             if (agencyDefinedEpoch == null) {
  633.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  634.             }
  635.             epoch = agencyDefinedEpoch;
  636.         }

  637.         // time field lengths
  638.         final int daySegmentLength = ((preambleField & 0x04) == 0x0) ? 2 : 3;
  639.         final int subMillisecondLength = (preambleField & 0x03) << 1;
  640.         if (subMillisecondLength == 6) {
  641.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  642.                                       formatByte(preambleField));
  643.         }
  644.         if (timeField.length != daySegmentLength + 4 + subMillisecondLength) {
  645.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  646.                                       timeField.length, daySegmentLength + 4 + subMillisecondLength);
  647.         }


  648.         int i   = 0;
  649.         int day = 0;
  650.         while (i < daySegmentLength) {
  651.             day = day * 256 + toUnsigned(timeField[i++]);
  652.         }

  653.         long milliInDay = 0l;
  654.         while (i < daySegmentLength + 4) {
  655.             milliInDay = milliInDay * 256 + toUnsigned(timeField[i++]);
  656.         }
  657.         final int milli   = (int) (milliInDay % 1000l);
  658.         final int seconds = (int) ((milliInDay - milli) / 1000l);

  659.         double subMilli = 0;
  660.         double divisor  = 1;
  661.         while (i < timeField.length) {
  662.             subMilli = subMilli * 256 + toUnsigned(timeField[i++]);
  663.             divisor *= 1000;
  664.         }

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

  668.     }

  669.     /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  670.      * <p>
  671.      * CCSDS Calendar Segmented Time Code is defined in the blue book:
  672.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  673.      * </p>
  674.      *
  675.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  676.      *
  677.      * @param preambleField field specifying the format, often not transmitted in
  678.      * data interfaces, as it is constant for a given data interface
  679.      * @param timeField byte array containing the time code
  680.      * @return an instance corresponding to the specified date
  681.      * @see #parseCCSDSCalendarSegmentedTimeCode(byte, byte[], TimeScale)
  682.      */
  683.     @DefaultDataContext
  684.     public static AbsoluteDate parseCCSDSCalendarSegmentedTimeCode(final byte preambleField, final byte[] timeField) {
  685.         return parseCCSDSCalendarSegmentedTimeCode(preambleField, timeField,
  686.                 DataContext.getDefault().getTimeScales().getUTC());
  687.     }

  688.     /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  689.      * <p>
  690.      * CCSDS Calendar Segmented Time Code is defined in the blue book:
  691.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  692.      * </p>
  693.      * @param preambleField field specifying the format, often not transmitted in
  694.      * data interfaces, as it is constant for a given data interface
  695.      * @param timeField byte array containing the time code
  696.      * @param utc      time scale used to compute date and time components.
  697.      * @return an instance corresponding to the specified date
  698.      * @since 10.1
  699.      */
  700.     public static AbsoluteDate parseCCSDSCalendarSegmentedTimeCode(
  701.             final byte preambleField,
  702.             final byte[] timeField,
  703.             final TimeScale utc) {

  704.         // time code identification
  705.         if ((preambleField & 0xF0) != 0x50) {
  706.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  707.                                       formatByte(preambleField));
  708.         }

  709.         // time field length
  710.         final int length = 7 + (preambleField & 0x07);
  711.         if (length == 14) {
  712.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  713.                                       formatByte(preambleField));
  714.         }
  715.         if (timeField.length != length) {
  716.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  717.                                       timeField.length, length);
  718.         }

  719.         // date part in the first four bytes
  720.         final DateComponents date;
  721.         if ((preambleField & 0x08) == 0x00) {
  722.             // month of year and day of month variation
  723.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  724.                                       toUnsigned(timeField[2]),
  725.                                       toUnsigned(timeField[3]));
  726.         } else {
  727.             // day of year variation
  728.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  729.                                       toUnsigned(timeField[2]) * 256 + toUnsigned(timeField[3]));
  730.         }

  731.         // time part from bytes 5 to last (between 7 and 13 depending on precision)
  732.         final TimeComponents time = new TimeComponents(toUnsigned(timeField[4]),
  733.                                                        toUnsigned(timeField[5]),
  734.                                                        toUnsigned(timeField[6]));
  735.         double subSecond = 0;
  736.         double divisor   = 1;
  737.         for (int i = 7; i < length; ++i) {
  738.             subSecond = subSecond * 100 + toUnsigned(timeField[i]);
  739.             divisor *= 100;
  740.         }

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

  742.     }

  743.     /** Decode a signed byte as an unsigned int value.
  744.      * @param b byte to decode
  745.      * @return an unsigned int value
  746.      */
  747.     private static int toUnsigned(final byte b) {
  748.         final int i = (int) b;
  749.         return (i < 0) ? 256 + i : i;
  750.     }

  751.     /** Format a byte as an hex string for error messages.
  752.      * @param data byte to format
  753.      * @return a formatted string
  754.      */
  755.     private static String formatByte(final byte data) {
  756.         return "0x" + Integer.toHexString(data).toUpperCase();
  757.     }

  758.     /** Build an instance corresponding to a Julian Day date.
  759.      * @param jd Julian day
  760.      * @param secondsSinceNoon seconds in the Julian day
  761.      * (BEWARE, Julian days start at noon, so 0.0 is noon)
  762.      * @param timeScale time scale in which the seconds in day are defined
  763.      * @return a new instant
  764.      */
  765.     public static AbsoluteDate createJDDate(final int jd, final double secondsSinceNoon,
  766.                                              final TimeScale timeScale) {
  767.         return new AbsoluteDate(new DateComponents(DateComponents.JULIAN_EPOCH, jd),
  768.                                 TimeComponents.H12, timeScale).shiftedBy(secondsSinceNoon);
  769.     }

  770.     /** Build an instance corresponding to a Modified Julian Day date.
  771.      * @param mjd modified Julian day
  772.      * @param secondsInDay seconds in the day
  773.      * @param timeScale time scale in which the seconds in day are defined
  774.      * @return a new instant
  775.      * @exception OrekitIllegalArgumentException if seconds number is out of range
  776.      */
  777.     public static AbsoluteDate createMJDDate(final int mjd, final double secondsInDay,
  778.                                              final TimeScale timeScale)
  779.         throws OrekitIllegalArgumentException {
  780.         final DateComponents dc = new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, mjd);
  781.         final TimeComponents tc;
  782.         if (secondsInDay >= Constants.JULIAN_DAY) {
  783.             // check we are really allowed to use this number of seconds
  784.             final int    secondsA = 86399; // 23:59:59, i.e. 59s in the last minute of the day
  785.             final double secondsB = secondsInDay - secondsA;
  786.             final TimeComponents safeTC = new TimeComponents(secondsA, 0.0);
  787.             final AbsoluteDate safeDate = new AbsoluteDate(dc, safeTC, timeScale);
  788.             if (timeScale.minuteDuration(safeDate) > 59 + secondsB) {
  789.                 // we are within the last minute of the day, the number of seconds is OK
  790.                 return safeDate.shiftedBy(secondsB);
  791.             } else {
  792.                 // let TimeComponents trigger an OrekitIllegalArgumentException
  793.                 // for the wrong number of seconds
  794.                 tc = new TimeComponents(secondsA, secondsB);
  795.             }
  796.         } else {
  797.             tc = new TimeComponents(secondsInDay);
  798.         }

  799.         // create the date
  800.         return new AbsoluteDate(dc, tc, timeScale);

  801.     }


  802.     /** Build an instance corresponding to a Julian Epoch (JE).
  803.      * <p>According to Lieske paper: <a
  804.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&amp;defaultprint=YES&amp;filetype=.pdf.">
  805.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
  806.      * vol. 73, no. 3, Mar. 1979, p. 282-284, Julian Epoch is related to Julian Ephemeris Date as:</p>
  807.      * <pre>
  808.      * JE = 2000.0 + (JED - 2451545.0) / 365.25
  809.      * </pre>
  810.      * <p>
  811.      * This method reverts the formula above and computes an {@code AbsoluteDate} from the Julian Epoch.
  812.      * </p>
  813.      *
  814.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  815.      *
  816.      * @param julianEpoch Julian epoch, like 2000.0 for defining the classical reference J2000.0
  817.      * @return a new instant
  818.      * @see #J2000_EPOCH
  819.      * @see #createBesselianEpoch(double)
  820.      * @see TimeScales#createJulianEpoch(double)
  821.      */
  822.     @DefaultDataContext
  823.     public static AbsoluteDate createJulianEpoch(final double julianEpoch) {
  824.         return DataContext.getDefault().getTimeScales().createJulianEpoch(julianEpoch);
  825.     }

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

  850.     /** Get a time-shifted date.
  851.      * <p>
  852.      * Calling this method is equivalent to call <code>new AbsoluteDate(this, dt)</code>.
  853.      * </p>
  854.      * @param dt time shift in seconds
  855.      * @return a new date, shifted with respect to instance (which is immutable)
  856.      * @see org.orekit.utils.PVCoordinates#shiftedBy(double)
  857.      * @see org.orekit.attitudes.Attitude#shiftedBy(double)
  858.      * @see org.orekit.orbits.Orbit#shiftedBy(double)
  859.      * @see org.orekit.propagation.SpacecraftState#shiftedBy(double)
  860.      */
  861.     public AbsoluteDate shiftedBy(final double dt) {
  862.         return new AbsoluteDate(this, dt);
  863.     }

  864.     /** Compute the physically elapsed duration between two instants.
  865.      * <p>The returned duration is the number of seconds physically
  866.      * elapsed between the two instants, measured in a regular time
  867.      * scale with respect to surface of the Earth (i.e either the {@link
  868.      * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
  869.      * GPSScale GPS scale}). It is the only method that gives a
  870.      * duration with a physical meaning.</p>
  871.      * <p>This method gives the same result (with less computation)
  872.      * as calling {@link #offsetFrom(AbsoluteDate, TimeScale)}
  873.      * with a second argument set to one of the regular scales cited
  874.      * above.</p>
  875.      * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
  876.      * double)} constructor.</p>
  877.      * @param instant instant to subtract from the instance
  878.      * @return offset in seconds between the two instants (positive
  879.      * if the instance is posterior to the argument)
  880.      * @see #offsetFrom(AbsoluteDate, TimeScale)
  881.      * @see #AbsoluteDate(AbsoluteDate, double)
  882.      */
  883.     public double durationFrom(final AbsoluteDate instant) {
  884.         return (epoch - instant.epoch) + (offset - instant.offset);
  885.     }

  886.     /** Compute the apparent clock offset between two instant <em>in the
  887.      * perspective of a specific {@link TimeScale time scale}</em>.
  888.      * <p>The offset is the number of seconds counted in the given
  889.      * time scale between the locations of the two instants, with
  890.      * all time scale irregularities removed (i.e. considering all
  891.      * days are exactly 86400 seconds long). This method will give
  892.      * a result that may not have a physical meaning if the time scale
  893.      * is irregular. For example since a leap second was introduced at
  894.      * the end of 2005, the apparent offset between 2005-12-31T23:59:59
  895.      * and 2006-01-01T00:00:00 is 1 second, but the physical duration
  896.      * of the corresponding time interval as returned by the {@link
  897.      * #durationFrom(AbsoluteDate)} method is 2 seconds.</p>
  898.      * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
  899.      * double, TimeScale)} constructor.</p>
  900.      * @param instant instant to subtract from the instance
  901.      * @param timeScale time scale with respect to which the offset should
  902.      * be computed
  903.      * @return apparent clock offset in seconds between the two instants
  904.      * (positive if the instance is posterior to the argument)
  905.      * @see #durationFrom(AbsoluteDate)
  906.      * @see #AbsoluteDate(AbsoluteDate, double, TimeScale)
  907.      */
  908.     public double offsetFrom(final AbsoluteDate instant, final TimeScale timeScale) {
  909.         final long   elapsedDurationA = epoch - instant.epoch;
  910.         final double elapsedDurationB = (offset         + timeScale.offsetFromTAI(this)) -
  911.                                         (instant.offset + timeScale.offsetFromTAI(instant));
  912.         return  elapsedDurationA + elapsedDurationB;
  913.     }

  914.     /** Compute the offset between two time scales at the current instant.
  915.      * <p>The offset is defined as <i>l₁-l₂</i>
  916.      * where <i>l₁</i> is the location of the instant in
  917.      * the <code>scale1</code> time scale and <i>l₂</i> is the
  918.      * location of the instant in the <code>scale2</code> time scale.</p>
  919.      * @param scale1 first time scale
  920.      * @param scale2 second time scale
  921.      * @return offset in seconds between the two time scales at the
  922.      * current instant
  923.      */
  924.     public double timeScalesOffset(final TimeScale scale1, final TimeScale scale2) {
  925.         return scale1.offsetFromTAI(this) - scale2.offsetFromTAI(this);
  926.     }

  927.     /** Convert the instance to a Java {@link java.util.Date Date}.
  928.      * <p>Conversion to the Date class induces a loss of precision because
  929.      * the Date class does not provide sub-millisecond information. Java Dates
  930.      * are considered to be locations in some times scales.</p>
  931.      * @param timeScale time scale to use
  932.      * @return a {@link java.util.Date Date} instance representing the location
  933.      * of the instant in the time scale
  934.      */
  935.     public Date toDate(final TimeScale timeScale) {
  936.         final double time = epoch + (offset + timeScale.offsetFromTAI(this));
  937.         return new Date(FastMath.round((time + 10957.5 * 86400.0) * 1000));
  938.     }

  939.     /** Split the instance into date/time components.
  940.      * @param timeScale time scale to use
  941.      * @return date/time components
  942.      */
  943.     public DateTimeComponents getComponents(final TimeScale timeScale) {

  944.         if (Double.isInfinite(offset)) {
  945.             // special handling for past and future infinity
  946.             if (offset < 0) {
  947.                 return new DateTimeComponents(DateComponents.MIN_EPOCH, TimeComponents.H00);
  948.             } else {
  949.                 return new DateTimeComponents(DateComponents.MAX_EPOCH,
  950.                                               new TimeComponents(23, 59, 59.999));
  951.             }
  952.         }

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

  957.         // split date and time
  958.         final long   carry = (long) FastMath.floor(sumAndResidual.getSum());
  959.         double offset2000B = (sumAndResidual.getSum() - carry) + sumAndResidual.getResidual();
  960.         long   offset2000A = epoch + carry + 43200l;
  961.         if (offset2000B < 0) {
  962.             offset2000A -= 1;
  963.             offset2000B += 1;
  964.         }
  965.         long time = offset2000A % 86400l;
  966.         if (time < 0l) {
  967.             time += 86400l;
  968.         }
  969.         final int date = (int) ((offset2000A - time) / 86400l);

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

  972.         // extract time element, accounting for leap seconds
  973.         final double leap = timeScale.insideLeap(this) ? timeScale.getLeap(this) : 0;
  974.         final int minuteDuration = timeScale.minuteDuration(this);
  975.         final TimeComponents timeComponents =
  976.                 TimeComponents.fromSeconds((int) time, offset2000B, leap, minuteDuration);

  977.         // build the components
  978.         return new DateTimeComponents(dateComponents, timeComponents);

  979.     }

  980.     /** Split the instance into date/time components for a local time.
  981.      *
  982.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  983.      *
  984.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  985.      * negative Westward UTC)
  986.      * @return date/time components
  987.      * @since 7.2
  988.      * @see #getComponents(int, TimeScale)
  989.      */
  990.     @DefaultDataContext
  991.     public DateTimeComponents getComponents(final int minutesFromUTC) {
  992.         return getComponents(minutesFromUTC,
  993.                 DataContext.getDefault().getTimeScales().getUTC());
  994.     }

  995.     /**
  996.      * Split the instance into date/time components for a local time.
  997.      *
  998.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  999.      *                       negative Westward UTC)
  1000.      * @param utc            time scale used to compute date and time components.
  1001.      * @return date/time components
  1002.      * @since 10.1
  1003.      */
  1004.     public DateTimeComponents getComponents(final int minutesFromUTC,
  1005.                                             final TimeScale utc) {

  1006.         final DateTimeComponents utcComponents = getComponents(utc);

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

  1011.         int minute = utcComponents.getTime().getMinute() + minutesFromUTC;
  1012.         final int hourShift;
  1013.         if (minute < 0) {
  1014.             hourShift = (minute - 59) / 60;
  1015.         } else if (minute > 59) {
  1016.             hourShift = minute / 60;
  1017.         } else {
  1018.             hourShift = 0;
  1019.         }
  1020.         minute -= 60 * hourShift;

  1021.         int hour = utcComponents.getTime().getHour() + hourShift;
  1022.         final int dayShift;
  1023.         if (hour < 0) {
  1024.             dayShift = (hour - 23) / 24;
  1025.         } else if (hour > 23) {
  1026.             dayShift = hour / 24;
  1027.         } else {
  1028.             dayShift = 0;
  1029.         }
  1030.         hour -= 24 * dayShift;

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

  1033.     }

  1034.     /** Split the instance into date/time components for a time zone.
  1035.      *
  1036.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1037.      *
  1038.      * @param timeZone time zone
  1039.      * @return date/time components
  1040.      * @since 7.2
  1041.      * @see #getComponents(TimeZone, TimeScale)
  1042.      */
  1043.     @DefaultDataContext
  1044.     public DateTimeComponents getComponents(final TimeZone timeZone) {
  1045.         return getComponents(timeZone, DataContext.getDefault().getTimeScales().getUTC());
  1046.     }

  1047.     /**
  1048.      * Split the instance into date/time components for a time zone.
  1049.      *
  1050.      * @param timeZone time zone
  1051.      * @param utc      time scale used to computed date and time components.
  1052.      * @return date/time components
  1053.      * @since 10.1
  1054.      */
  1055.     public DateTimeComponents getComponents(final TimeZone timeZone,
  1056.                                             final TimeScale utc) {
  1057.         final AbsoluteDate javaEpoch = new AbsoluteDate(DateComponents.JAVA_EPOCH, utc);
  1058.         final long milliseconds = FastMath.round(1000 * offsetFrom(javaEpoch, utc));
  1059.         return getComponents(timeZone.getOffset(milliseconds) / 60000, utc);
  1060.     }

  1061.     /** Compare the instance with another date.
  1062.      * @param date other date to compare the instance to
  1063.      * @return a negative integer, zero, or a positive integer as this date
  1064.      * is before, simultaneous, or after the specified date.
  1065.      */
  1066.     public int compareTo(final AbsoluteDate date) {
  1067.         final double duration = durationFrom(date);
  1068.         if (!Double.isNaN(duration)) {
  1069.             return Double.compare(duration, 0.0);
  1070.         }
  1071.         // both dates are infinity or one is NaN or both are NaN
  1072.         return Double.compare(offset, date.offset);
  1073.     }

  1074.     /** {@inheritDoc} */
  1075.     public AbsoluteDate getDate() {
  1076.         return this;
  1077.     }

  1078.     /** Check if the instance represents the same time as another instance.
  1079.      * @param date other date
  1080.      * @return true if the instance and the other date refer to the same instant
  1081.      */
  1082.     public boolean equals(final Object date) {

  1083.         if (date == this) {
  1084.             // first fast check
  1085.             return true;
  1086.         }

  1087.         if (date instanceof AbsoluteDate) {
  1088.             return durationFrom((AbsoluteDate) date) == 0;
  1089.         }

  1090.         return false;

  1091.     }

  1092.     /** Check if the instance represents the same time as another.
  1093.      * @param other the instant to compare this date to
  1094.      * @return true if the instance and the argument refer to the same instant
  1095.      * @see #isCloseTo(TimeStamped, double)
  1096.      * @since 10.1
  1097.      */
  1098.     public boolean isEqualTo(final TimeStamped other) {
  1099.         return this.equals(other.getDate());
  1100.     }

  1101.     /** Check if the instance time is close to another.
  1102.      * @param other the instant to compare this date to
  1103.      * @param tolerance the separation, in seconds, under which the two instants will be considered close to each other
  1104.      * @return true if the duration between the instance and the argument is strictly below the tolerance
  1105.      * @see #isEqualTo(TimeStamped)
  1106.      * @since 10.1
  1107.      */
  1108.     public boolean isCloseTo(final TimeStamped other, final double tolerance) {
  1109.         return FastMath.abs(this.durationFrom(other.getDate())) < tolerance;
  1110.     }

  1111.     /** Check if the instance represents a time that is strictly before another.
  1112.      * @param other the instant to compare this date to
  1113.      * @return true if the instance is strictly before the argument when ordering chronologically
  1114.      * @see #isBeforeOrEqualTo(TimeStamped)
  1115.      * @since 10.1
  1116.      */
  1117.     public boolean isBefore(final TimeStamped other) {
  1118.         return this.compareTo(other.getDate()) < 0;
  1119.     }

  1120.     /** Check if the instance represents a time that is strictly after another.
  1121.      * @param other the instant to compare this date to
  1122.      * @return true if the instance is strictly after the argument when ordering chronologically
  1123.      * @see #isAfterOrEqualTo(TimeStamped)
  1124.      * @since 10.1
  1125.      */
  1126.     public boolean isAfter(final TimeStamped other) {
  1127.         return this.compareTo(other.getDate()) > 0;
  1128.     }

  1129.     /** Check if the instance represents a time that is before or equal to another.
  1130.      * @param other the instant to compare this date to
  1131.      * @return true if the instance is before (or equal to) the argument when ordering chronologically
  1132.      * @see #isBefore(TimeStamped)
  1133.      * @since 10.1
  1134.      */
  1135.     public boolean isBeforeOrEqualTo(final TimeStamped other) {
  1136.         return this.isEqualTo(other) || this.isBefore(other);
  1137.     }

  1138.     /** Check if the instance represents a time that is after or equal to another.
  1139.      * @param other the instant to compare this date to
  1140.      * @return true if the instance is after (or equal to) the argument when ordering chronologically
  1141.      * @see #isAfterOrEqualTo(TimeStamped)
  1142.      * @since 10.1
  1143.      */
  1144.     public boolean isAfterOrEqualTo(final TimeStamped other) {
  1145.         return this.isEqualTo(other) || this.isAfter(other);
  1146.     }

  1147.     /** Check if the instance represents a time that is strictly between two others representing
  1148.      * the boundaries of a time span. The two boundaries can be provided in any order: in other words,
  1149.      * whether <code>boundary</code> represents a time that is before or after <code>otherBoundary</code> will
  1150.      * not change the result of this method.
  1151.      * @param boundary one end of the time span
  1152.      * @param otherBoundary the other end of the time span
  1153.      * @return true if the instance is strictly between the two arguments when ordering chronologically
  1154.      * @see #isBetweenOrEqualTo(TimeStamped, TimeStamped)
  1155.      * @since 10.1
  1156.      */
  1157.     public boolean isBetween(final TimeStamped boundary, final TimeStamped otherBoundary) {
  1158.         final TimeStamped beginning;
  1159.         final TimeStamped end;
  1160.         if (boundary.getDate().isBefore(otherBoundary)) {
  1161.             beginning = boundary;
  1162.             end = otherBoundary;
  1163.         } else {
  1164.             beginning = otherBoundary;
  1165.             end = boundary;
  1166.         }
  1167.         return this.isAfter(beginning) && this.isBefore(end);
  1168.     }

  1169.     /** Check if the instance represents a time that is between two others representing
  1170.      * the boundaries of a time span, or equal to one of them. The two boundaries can be provided in any order:
  1171.      * in other words, whether <code>boundary</code> represents a time that is before or after
  1172.      * <code>otherBoundary</code> will not change the result of this method.
  1173.      * @param boundary one end of the time span
  1174.      * @param otherBoundary the other end of the time span
  1175.      * @return true if the instance is between the two arguments (or equal to at least one of them)
  1176.      * when ordering chronologically
  1177.      * @see #isBetween(TimeStamped, TimeStamped)
  1178.      * @since 10.1
  1179.      */
  1180.     public boolean isBetweenOrEqualTo(final TimeStamped boundary, final TimeStamped otherBoundary) {
  1181.         return this.isEqualTo(boundary) || this.isEqualTo(otherBoundary) || this.isBetween(boundary, otherBoundary);
  1182.     }

  1183.     /** Get a hashcode for this date.
  1184.      * @return hashcode
  1185.      */
  1186.     public int hashCode() {
  1187.         final long l = Double.doubleToLongBits(durationFrom(ARBITRARY_EPOCH));
  1188.         return (int) (l ^ (l >>> 32));
  1189.     }

  1190.     /**
  1191.      * Get a String representation of the instant location with up to 16 digits of
  1192.      * precision for the seconds value.
  1193.      *
  1194.      * <p> Since this method is used in exception messages and error handling every
  1195.      * effort is made to return some representation of the instant. If UTC is available
  1196.      * from the default data context then it is used to format the string in UTC. If not
  1197.      * then TAI is used. Finally if the prior attempts fail this method falls back to
  1198.      * converting this class's internal representation to a string.
  1199.      *
  1200.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1201.      *
  1202.      * @return a string representation of the instance, in ISO-8601 format if UTC is
  1203.      * available from the default data context.
  1204.      * @see #toString(TimeScale)
  1205.      * @see #toStringRfc3339(TimeScale)
  1206.      * @see DateTimeComponents#toString(int, int)
  1207.      */
  1208.     @DefaultDataContext
  1209.     public String toString() {
  1210.         // CHECKSTYLE: stop IllegalCatch check
  1211.         try {
  1212.             // try to use UTC first at that is likely most familiar to the user.
  1213.             return toString(DataContext.getDefault().getTimeScales().getUTC()) + "Z";
  1214.         } catch (RuntimeException e1) {
  1215.             // catch OrekitException, OrekitIllegalStateException, etc.
  1216.             try {
  1217.                 // UTC failed, try to use TAI
  1218.                 return toString(new TAIScale()) + " TAI";
  1219.             } catch (RuntimeException e2) {
  1220.                 // catch OrekitException, OrekitIllegalStateException, etc.
  1221.                 // Likely failed to convert to ymdhms.
  1222.                 // Give user some indication of what time it is.
  1223.                 try {
  1224.                     return "(" + this.epoch + " + " + this.offset + ") seconds past epoch";
  1225.                 } catch (RuntimeException e3) {
  1226.                     // give up and throw an exception
  1227.                     e2.addSuppressed(e3);
  1228.                     e1.addSuppressed(e2);
  1229.                     throw e1;
  1230.                 }
  1231.             }
  1232.         }
  1233.         // CHECKSTYLE: resume IllegalCatch check
  1234.     }

  1235.     /**
  1236.      * Get a String representation of the instant location in ISO-8601 format without the
  1237.      * UTC offset and with up to 16 digits of precision for the seconds value.
  1238.      *
  1239.      * @param timeScale time scale to use
  1240.      * @return a string representation of the instance.
  1241.      * @see #toStringRfc3339(TimeScale)
  1242.      * @see DateTimeComponents#toString(int, int)
  1243.      */
  1244.     public String toString(final TimeScale timeScale) {
  1245.         return getComponents(timeScale).toStringWithoutUtcOffset();
  1246.     }

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

  1263.     /**
  1264.      * Get a String representation of the instant location for a local time.
  1265.      *
  1266.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1267.      *                       negative Westward UTC).
  1268.      * @param utc            time scale used to compute date and time components.
  1269.      * @return string representation of the instance, in ISO-8601 format with milliseconds
  1270.      * accuracy
  1271.      * @since 10.1
  1272.      * @see #getComponents(int, TimeScale)
  1273.      * @see DateTimeComponents#toString(int, int)
  1274.      */
  1275.     public String toString(final int minutesFromUTC, final TimeScale utc) {
  1276.         final int minuteDuration = utc.minuteDuration(this);
  1277.         return getComponents(minutesFromUTC, utc).toString(minuteDuration);
  1278.     }

  1279.     /** Get a String representation of the instant location for a time zone.
  1280.      *
  1281.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1282.      *
  1283.      * @param timeZone time zone
  1284.      * @return string representation of the instance,
  1285.      * in ISO-8601 format with milliseconds accuracy
  1286.      * @since 7.2
  1287.      * @see #toString(TimeZone, TimeScale)
  1288.      */
  1289.     @DefaultDataContext
  1290.     public String toString(final TimeZone timeZone) {
  1291.         return toString(timeZone, DataContext.getDefault().getTimeScales().getUTC());
  1292.     }

  1293.     /**
  1294.      * Get a String representation of the instant location for a time zone.
  1295.      *
  1296.      * @param timeZone time zone
  1297.      * @param utc      time scale used to compute date and time components.
  1298.      * @return string representation of the instance, in ISO-8601 format with milliseconds
  1299.      * accuracy
  1300.      * @since 10.1
  1301.      * @see #getComponents(TimeZone, TimeScale)
  1302.      * @see DateTimeComponents#toString(int, int)
  1303.      */
  1304.     public String toString(final TimeZone timeZone, final TimeScale utc) {
  1305.         final int minuteDuration = utc.minuteDuration(this);
  1306.         return getComponents(timeZone, utc).toString(minuteDuration);
  1307.     }

  1308.     /**
  1309.      * Represent the given date as a string according to the format in RFC 3339. RFC3339
  1310.      * is a restricted subset of ISO 8601 with a well defined grammar. Enough digits are
  1311.      * included in the seconds value to avoid rounding up to the next minute.
  1312.      *
  1313.      * <p>This method is different than {@link AbsoluteDate#toString(TimeScale)} in that
  1314.      * it includes a {@code "Z"} at the end to indicate the time zone and enough precision
  1315.      * to represent the point in time without rounding up to the next minute.
  1316.      *
  1317.      * <p>RFC3339 is unable to represent BC years, years of 10000 or more, time zone
  1318.      * offsets of 100 hours or more, or NaN. In these cases the value returned from this
  1319.      * method will not be valid RFC3339 format.
  1320.      *
  1321.      * @param utc time scale.
  1322.      * @return RFC 3339 format string.
  1323.      * @see <a href="https://tools.ietf.org/html/rfc3339#page-8">RFC 3339</a>
  1324.      * @see DateTimeComponents#toStringRfc3339()
  1325.      * @see #toString(TimeScale)
  1326.      * @see #getComponents(TimeScale)
  1327.      */
  1328.     public String toStringRfc3339(final TimeScale utc) {
  1329.         return this.getComponents(utc).toStringRfc3339();
  1330.     }

  1331.     /**
  1332.      * Return a string representation of this date-time, rounded to the given precision.
  1333.      *
  1334.      * <p>The format used is ISO8601 without the UTC offset.</p>
  1335.      *
  1336.      * <p>Calling {@code toStringWithoutUtcOffset(DataContext.getDefault().getTimeScales().getUTC(),
  1337.      * 3)} will emulate the behavior of {@link #toString()} in Orekit 10 and earlier. Note
  1338.      * this method is more accurate as it correctly handles rounding during leap seconds.
  1339.      *
  1340.      * @param timeScale      to use to compute components.
  1341.      * @param fractionDigits the number of digits to include after the decimal point in
  1342.      *                       the string representation of the seconds. The date and time
  1343.      *                       is first rounded as necessary. {@code fractionDigits} must be
  1344.      *                       greater than or equal to {@code 0}.
  1345.      * @return string representation of this date, time, and UTC offset
  1346.      * @see #toString(TimeScale)
  1347.      * @see #toStringRfc3339(TimeScale)
  1348.      * @see DateTimeComponents#toString(int, int)
  1349.      * @see DateTimeComponents#toStringWithoutUtcOffset(int, int)
  1350.      * @since 11.1
  1351.      */
  1352.     public String toStringWithoutUtcOffset(final TimeScale timeScale,
  1353.                                            final int fractionDigits) {
  1354.         return this.getComponents(timeScale)
  1355.                 .toStringWithoutUtcOffset(timeScale.minuteDuration(this), fractionDigits);
  1356.     }

  1357. }