FieldAbsoluteDate.java

  1. /* Copyright 2002-2024 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.time.Instant;
  19. import java.util.Date;
  20. import java.util.TimeZone;

  21. import org.hipparchus.CalculusFieldElement;
  22. import org.hipparchus.Field;
  23. import org.hipparchus.FieldElement;
  24. import org.hipparchus.analysis.differentiation.Derivative;
  25. import org.hipparchus.complex.Complex;
  26. import org.hipparchus.util.FastMath;
  27. import org.hipparchus.util.MathUtils;
  28. import org.hipparchus.util.MathUtils.FieldSumAndResidual;
  29. import org.hipparchus.util.MathUtils.SumAndResidual;
  30. import org.orekit.annotation.DefaultDataContext;
  31. import org.orekit.data.DataContext;
  32. import org.orekit.errors.OrekitException;
  33. import org.orekit.errors.OrekitMessages;
  34. import org.orekit.utils.Constants;

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

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

  105.     /** Reference epoch in seconds from 2000-01-01T12:00:00 TAI.
  106.      * <p>Beware, it is not {@link #getJ2000Epoch(Field)} since it is in TAI and not in TT.</p> */
  107.     private final long epoch;

  108.     /** Offset from the reference epoch in seconds. */
  109.     private final  T offset;

  110.     /** Field used by default.*/
  111.     private Field<T> field;

  112.     /** Build an instance from an AbsoluteDate.
  113.      * @param field used by default
  114.      * @param date AbsoluteDate to instantiate as a FieldAbsoluteDate
  115.      */
  116.     public FieldAbsoluteDate(final Field<T> field, final AbsoluteDate date) {
  117.         this.field  = field;
  118.         this.epoch  = date.getEpoch();
  119.         this.offset = field.getZero().add(date.getOffset());
  120.     }

  121.     /** Create an instance with a default value ({@link #getJ2000Epoch(Field)}).
  122.      *
  123.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  124.      *
  125.      * @param field field used by default
  126.      * @see #FieldAbsoluteDate(Field, AbsoluteDate)
  127.      */
  128.     @DefaultDataContext
  129.     public FieldAbsoluteDate(final Field<T> field) {
  130.         final FieldAbsoluteDate<T> j2000 = getJ2000Epoch(field);
  131.         this.field  = j2000.field;
  132.         this.epoch  = j2000.epoch;
  133.         this.offset = j2000.offset;
  134.     }

  135.     /** Build an instance from an elapsed duration since to another instant.
  136.      * <p>It is important to note that the elapsed duration is <em>not</em>
  137.      * the difference between two readings on a time scale. As an example,
  138.      * the duration between the two instants leading to the readings
  139.      * 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the {@link UTCScale UTC}
  140.      * time scale is <em>not</em> 1 second, but a stop watch would have measured
  141.      * an elapsed duration of 2 seconds between these two instances because a leap
  142.      * second was introduced at the end of 2005 in this time scale.</p>
  143.      * <p>This constructor is the reverse of the {@link #durationFrom(FieldAbsoluteDate)}
  144.      * method.</p>
  145.      * @param since start instant of the measured duration
  146.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  147.      * instant, as measured in a regular time scale
  148.      * @see #durationFrom(FieldAbsoluteDate)
  149.      */
  150.     public FieldAbsoluteDate(final FieldAbsoluteDate<T> since, final T elapsedDuration) {
  151.         this.field = since.field;
  152.         // Use 2Sum for high precision.
  153.         final FieldSumAndResidual<T> sumAndResidual = MathUtils.twoSum(since.offset, elapsedDuration);
  154.         if (Double.isInfinite(sumAndResidual.getSum().getReal())) {
  155.             offset = sumAndResidual.getSum();
  156.             epoch = (sumAndResidual.getSum().getReal() < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
  157.         } else {
  158.             final long dl = (long) FastMath.floor(sumAndResidual.getSum().getReal());
  159.             final T regularOffset = sumAndResidual.getSum().subtract(dl).add(sumAndResidual.getResidual());
  160.             if (regularOffset.getReal() >= 0) {
  161.                 // regular case, the offset is between 0.0 and 1.0
  162.                 offset = regularOffset;
  163.                 epoch = since.epoch + dl;
  164.             } else {
  165.                 // very rare case, the offset is just before a whole second
  166.                 // we will loose some bits of accuracy when adding 1 second
  167.                 // but this will ensure the offset remains in the [0.0; 1.0] interval
  168.                 offset = regularOffset.add(1.0);
  169.                 epoch  = since.epoch + dl - 1;
  170.             }
  171.         }
  172.     }

  173.     /** Build an instance from a location (parsed from a string) in a {@link TimeScale time scale}.
  174.      * <p>
  175.      * The supported formats for location are mainly the ones defined in ISO-8601 standard,
  176.      * the exact subset is explained in {@link DateTimeComponents#parseDateTime(String)},
  177.      * {@link DateComponents#parseDate(String)} and {@link TimeComponents#parseTime(String)}.
  178.      * </p>
  179.      * <p>
  180.      * As CCSDS ASCII calendar segmented time code is a trimmed down version of ISO-8601,
  181.      * it is also supported by this constructor.
  182.      * </p>
  183.      * @param field field utilized by default
  184.      * @param location location in the time scale, must be in a supported format
  185.      * @param timeScale time scale
  186.      * @exception IllegalArgumentException if location string is not in a supported format
  187.      */
  188.     public FieldAbsoluteDate(final Field<T> field, final String location, final TimeScale timeScale) {
  189.         this(field, DateTimeComponents.parseDateTime(location), timeScale);
  190.     }

  191.     /** Build an instance from a location in a {@link TimeScale time scale}.
  192.      * @param field field utilized by default
  193.      * @param location location in the time scale
  194.      * @param timeScale time scale
  195.      */
  196.     public FieldAbsoluteDate(final Field<T> field, final DateTimeComponents location, final TimeScale timeScale) {
  197.         this(field, location.getDate(), location.getTime(), timeScale);
  198.     }

  199.     /** Build an instance from a location in a {@link TimeScale time scale}.
  200.      * @param field field utilized by default
  201.      * @param date date location in the time scale
  202.      * @param time time location in the time scale
  203.      * @param timeScale time scale
  204.      */
  205.     public FieldAbsoluteDate(final Field<T> field, final DateComponents date, final TimeComponents time,
  206.                              final TimeScale timeScale) {
  207.         final double seconds  = time.getSecond();
  208.         final double tsOffset = timeScale.offsetToTAI(date, time);

  209.         // Use 2Sum for high precision.
  210.         final SumAndResidual sumAndResidual = MathUtils.twoSum(seconds, tsOffset);
  211.         final long dl = (long) FastMath.floor(sumAndResidual.getSum());
  212.         final T regularOffset = field.getZero().add((sumAndResidual.getSum() - dl) + sumAndResidual.getResidual());
  213.         if (regularOffset.getReal() >= 0) {
  214.             // regular case, the offset is between 0.0 and 1.0
  215.             offset = regularOffset;
  216.             epoch  = 60l * ((date.getJ2000Day() * 24l + time.getHour()) * 60l +
  217.                             time.getMinute() - time.getMinutesFromUTC() - 720l) + dl;
  218.         } else {
  219.             // very rare case, the offset is just before a whole second
  220.             // we will loose some bits of accuracy when adding 1 second
  221.             // but this will ensure the offset remains in the [0.0; 1.0] interval
  222.             offset = regularOffset.add(1.0);
  223.             epoch  = 60l * ((date.getJ2000Day() * 24l + time.getHour()) * 60l +
  224.                             time.getMinute() - time.getMinutesFromUTC() - 720l) + dl - 1;
  225.         }
  226.         this.field = field;

  227.     }

  228.     /** Build an instance from a location in a {@link TimeScale time scale}.
  229.      * @param field field utilized by default
  230.      * @param year year number (may be 0 or negative for BC years)
  231.      * @param month month number from 1 to 12
  232.      * @param day day number from 1 to 31
  233.      * @param hour hour number from 0 to 23
  234.      * @param minute minute number from 0 to 59
  235.      * @param second second number from 0.0 to 60.0 (excluded)
  236.      * @param timeScale time scale
  237.      * @exception IllegalArgumentException if inconsistent arguments
  238.      * are given (parameters out of range)
  239.      */
  240.     public FieldAbsoluteDate(final Field<T> field, final int year, final int month, final int day,
  241.                              final int hour, final int minute, final double second,
  242.                              final TimeScale timeScale) throws IllegalArgumentException {
  243.         this(field, new DateComponents(year, month, day), new TimeComponents(hour, minute, second), timeScale);
  244.     }

  245.     /** Build an instance from a location in a {@link TimeScale time scale}.
  246.      * @param field field utilized by default
  247.      * @param year year number (may be 0 or negative for BC years)
  248.      * @param month month enumerate
  249.      * @param day day number from 1 to 31
  250.      * @param hour hour number from 0 to 23
  251.      * @param minute minute number from 0 to 59
  252.      * @param second second number from 0.0 to 60.0 (excluded)
  253.      * @param timeScale time scale
  254.      * @exception IllegalArgumentException if inconsistent arguments
  255.      * are given (parameters out of range)
  256.      */
  257.     public FieldAbsoluteDate(final Field<T> field, final int year, final Month month, final int day,
  258.                              final int hour, final int minute, final double second,
  259.                              final TimeScale timeScale) throws IllegalArgumentException {
  260.         this(field, new DateComponents(year, month, day), new TimeComponents(hour, minute, second), timeScale);
  261.     }

  262.     /** Build an instance from a location in a {@link TimeScale time scale}.
  263.      * <p>The hour is set to 00:00:00.000.</p>
  264.      * @param field field utilized by default
  265.      * @param date date location in the time scale
  266.      * @param timeScale time scale
  267.      * @exception IllegalArgumentException if inconsistent arguments
  268.      * are given (parameters out of range)
  269.      */
  270.     public FieldAbsoluteDate(final Field<T> field, final DateComponents date, final TimeScale timeScale)
  271.                     throws IllegalArgumentException {
  272.         this(field, date, TimeComponents.H00, timeScale);
  273.     }

  274.     /** Build an instance from a location in a {@link TimeScale time scale}.
  275.      * <p>The hour is set to 00:00:00.000.</p>
  276.      * @param field field utilized by default
  277.      * @param year year number (may be 0 or negative for BC years)
  278.      * @param month month number from 1 to 12
  279.      * @param day day number from 1 to 31
  280.      * @param timeScale time scale
  281.      * @exception IllegalArgumentException if inconsistent arguments
  282.      * are given (parameters out of range)
  283.      */
  284.     public FieldAbsoluteDate(final Field<T> field, final int year, final int month, final int day,
  285.                              final TimeScale timeScale) throws IllegalArgumentException {
  286.         this(field, new DateComponents(year, month, day), TimeComponents.H00, timeScale);
  287.     }

  288.     /** Build an instance from a location in a {@link TimeScale time scale}.
  289.      * <p>The hour is set to 00:00:00.000.</p>
  290.      * @param field field utilized by default
  291.      * @param year year number (may be 0 or negative for BC years)
  292.      * @param month month enumerate
  293.      * @param day day number from 1 to 31
  294.      * @param timeScale time scale
  295.      * @exception IllegalArgumentException if inconsistent arguments
  296.      * are given (parameters out of range)
  297.      */
  298.     public FieldAbsoluteDate(final Field<T> field, final int year, final Month month, final int day,
  299.                              final TimeScale timeScale) throws IllegalArgumentException {
  300.         this(field, new DateComponents(year, month, day), TimeComponents.H00, timeScale);
  301.     }

  302.     /** Build an instance from a location in a {@link TimeScale time scale}.
  303.      * @param field field utilized as default
  304.      * @param location location in the time scale
  305.      * @param timeScale time scale
  306.      */
  307.     public FieldAbsoluteDate(final Field<T> field, final Date location, final TimeScale timeScale) {
  308.         this(field, new DateComponents(DateComponents.JAVA_EPOCH,
  309.                                        (int) (location.getTime() / 86400000l)),
  310.              new TimeComponents(0.001 * (location.getTime() % 86400000l)),
  311.              timeScale);
  312.     }

  313.     /** Build an instance from an {@link Instant instant} in a {@link TimeScale time scale}.
  314.      * @param field field utilized as default
  315.      * @param instant instant in the time scale
  316.      * @param timeScale time scale
  317.      * @since 12.0
  318.      */
  319.     public FieldAbsoluteDate(final Field<T> field, final Instant instant, final TimeScale timeScale) {
  320.         this(field, new DateComponents(DateComponents.JAVA_EPOCH,
  321.                                        (int) (instant.getEpochSecond() / 86400l)),
  322.              instantToTimeComponents(instant),
  323.              timeScale);
  324.     }

  325.     /** Build an instance from an elapsed duration since to another instant.
  326.      * <p>It is important to note that the elapsed duration is <em>not</em>
  327.      * the difference between two readings on a time scale.
  328.      * @param since start instant of the measured duration
  329.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  330.      * instant, as measured in a regular time scale
  331.      */
  332.     public FieldAbsoluteDate(final FieldAbsoluteDate<T> since, final double elapsedDuration) {
  333.         this(since.epoch, elapsedDuration, since.offset);
  334.     }


  335.     /** Build an instance from an elapsed duration since to another instant.
  336.      * <p>It is important to note that the elapsed duration is <em>not</em>
  337.      * the difference between two readings on a time scale.
  338.      * @param since start instant of the measured duration
  339.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  340.      * instant, as measured in a regular time scale
  341.      */
  342.     public FieldAbsoluteDate(final AbsoluteDate since, final T elapsedDuration) {
  343.         this(since.getEpoch(), since.getOffset(), elapsedDuration);
  344.     }

  345.     /** Build an instance from an apparent clock offset with respect to another
  346.      * instant <em>in the perspective of a specific {@link TimeScale time scale}</em>.
  347.      * <p>It is important to note that the apparent clock offset <em>is</em> the
  348.      * difference between two readings on a time scale and <em>not</em> an elapsed
  349.      * duration. As an example, the apparent clock offset between the two instants
  350.      * leading to the readings 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the
  351.      * {@link UTCScale UTC} time scale is 1 second, but the elapsed duration is 2
  352.      * seconds because a leap second has been introduced at the end of 2005 in this
  353.      * time scale.</p>
  354.      * <p>This constructor is the reverse of the {@link #offsetFrom(FieldAbsoluteDate,
  355.      * TimeScale)} method.</p>
  356.      * @param reference reference instant
  357.      * @param apparentOffset apparent clock offset from the reference instant
  358.      * (difference between two readings in the specified time scale)
  359.      * @param timeScale time scale with respect to which the offset is defined
  360.      * @see #offsetFrom(FieldAbsoluteDate, TimeScale)
  361.      */
  362.     public FieldAbsoluteDate(final FieldAbsoluteDate<T> reference, final double apparentOffset, final TimeScale timeScale) {
  363.         this(reference.field, new DateTimeComponents(reference.getComponents(timeScale), apparentOffset),
  364.              timeScale);
  365.     }

  366.     /** Build an instance from mixed double and field raw components.
  367.      * @param epoch reference epoch in seconds from 2000-01-01T12:00:00 TAI
  368.      * @param tA double part of offset since reference epoch
  369.      * @param tB field part of offset since reference epoch
  370.      * @since 9.3
  371.      */
  372.     private FieldAbsoluteDate(final long epoch, final double tA, final T tB) {
  373.         this.field = tB.getField();
  374.         // Use 2Sum for high precision.
  375.         final FieldSumAndResidual<T> sumAndResidual = MathUtils.twoSum(field.getZero().add(tA), tB);
  376.         if (Double.isInfinite(sumAndResidual.getSum().getReal())) {
  377.             this.offset = sumAndResidual.getSum();
  378.             this.epoch  = (sumAndResidual.getSum().getReal() < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
  379.         } else {
  380.             final long dl = (long) FastMath.floor(sumAndResidual.getSum().getReal());
  381.             final T regularOffset = sumAndResidual.getSum().subtract(dl).add(sumAndResidual.getResidual());
  382.             if (regularOffset.getReal() >= 0) {
  383.                 // regular case, the offset is between 0.0 and 1.0
  384.                 this.offset = regularOffset;
  385.                 this.epoch  = epoch + dl;
  386.             } else {
  387.                 // very rare case, the offset is just before a whole second
  388.                 // we will lose some bits of accuracy when adding 1 second
  389.                 // but this will ensure the offset remains in the [0.0; 1.0) interval
  390.                 this.offset = regularOffset.add(1.0);
  391.                 this.epoch  = epoch + dl - 1;
  392.             }
  393.         }
  394.     }

  395.     /** Extract time components from an instant within the day.
  396.      * @param instant instant to extract the number of seconds within the day
  397.      * @return time components
  398.      */
  399.     private static TimeComponents instantToTimeComponents(final Instant instant) {
  400.         final int secInDay = (int) (instant.getEpochSecond() % 86400l);
  401.         return new TimeComponents(secInDay, 1.0e-9 * instant.getNano());
  402.     }

  403.     /** Build an instance from a CCSDS Unsegmented Time Code (CUC).
  404.      * <p>
  405.      * CCSDS Unsegmented Time Code is defined in the blue book:
  406.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  407.      * </p>
  408.      * <p>
  409.      * If the date to be parsed is formatted using version 3 of the standard
  410.      * (CCSDS 301.0-B-3 published in 2002) or if the extension of the preamble
  411.      * field introduced in version 4 of the standard is not used, then the
  412.      * {@code preambleField2} parameter can be set to 0.
  413.      * </p>
  414.      *
  415.      * <p>This method uses the {@link DataContext#getDefault() default data context} if
  416.      * the CCSDS epoch is used.
  417.      *
  418.      * @param field field for the components
  419.      * @param preambleField1 first byte of the field specifying the format, often
  420.      * not transmitted in data interfaces, as it is constant for a given data interface
  421.      * @param preambleField2 second byte of the field specifying the format
  422.      * (added in revision 4 of the CCSDS standard in 2010), often not transmitted in data
  423.      * interfaces, as it is constant for a given data interface (value ignored if presence
  424.      * not signaled in {@code preambleField1})
  425.      * @param timeField byte array containing the time code
  426.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  427.      * specifies the {@link #getCCSDSEpoch(Field) CCSDS reference epoch} is used (and hence
  428.      * may be null in this case)
  429.      * @return an instance corresponding to the specified date
  430.      * @param <T> the type of the field elements
  431.      * @see #parseCCSDSUnsegmentedTimeCode(Field, byte, byte, byte[], FieldAbsoluteDate,
  432.      * FieldAbsoluteDate)
  433.      */
  434.     @DefaultDataContext
  435.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> parseCCSDSUnsegmentedTimeCode(final Field<T> field,
  436.                                                                                                          final byte preambleField1,
  437.                                                                                                          final byte preambleField2,
  438.                                                                                                          final byte[] timeField,
  439.                                                                                                          final FieldAbsoluteDate<T> agencyDefinedEpoch) {
  440.         return parseCCSDSUnsegmentedTimeCode(field, preambleField1, preambleField2,
  441.                                              timeField, agencyDefinedEpoch,
  442.                                              new FieldAbsoluteDate<>(
  443.                                                              field,
  444.                                                              DataContext.getDefault().getTimeScales().getCcsdsEpoch()));
  445.     }

  446.     /**
  447.      * Build an instance from a CCSDS Unsegmented Time Code (CUC).
  448.      * <p>
  449.      * CCSDS Unsegmented Time Code is defined in the blue book: CCSDS Time Code Format
  450.      * (CCSDS 301.0-B-4) published in November 2010
  451.      * </p>
  452.      * <p>
  453.      * If the date to be parsed is formatted using version 3 of the standard (CCSDS
  454.      * 301.0-B-3 published in 2002) or if the extension of the preamble field introduced
  455.      * in version 4 of the standard is not used, then the {@code preambleField2} parameter
  456.      * can be set to 0.
  457.      * </p>
  458.      *
  459.      * @param <T>                the type of the field elements
  460.      * @param field              field for the components
  461.      * @param preambleField1     first byte of the field specifying the format, often not
  462.      *                           transmitted in data interfaces, as it is constant for a
  463.      *                           given data interface
  464.      * @param preambleField2     second byte of the field specifying the format (added in
  465.      *                           revision 4 of the CCSDS standard in 2010), often not
  466.      *                           transmitted in data interfaces, as it is constant for a
  467.      *                           given data interface (value ignored if presence not
  468.      *                           signaled in {@code preambleField1})
  469.      * @param timeField          byte array containing the time code
  470.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field specifies
  471.      *                           the CCSDS reference epoch is used (and hence may be null
  472.      *                           in this case)
  473.      * @param ccsdsEpoch         reference epoch, ignored if the preamble field specifies
  474.      *                           the agency epoch is used.
  475.      * @return an instance corresponding to the specified date
  476.      * @since 10.1
  477.      */
  478.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> parseCCSDSUnsegmentedTimeCode(
  479.                                                                                                          final Field<T> field,
  480.                                                                                                          final byte preambleField1,
  481.                                                                                                          final byte preambleField2,
  482.                                                                                                          final byte[] timeField,
  483.                                                                                                          final FieldAbsoluteDate<T> agencyDefinedEpoch,
  484.                                                                                                          final FieldAbsoluteDate<T> ccsdsEpoch) {

  485.         // time code identification and reference epoch
  486.         final FieldAbsoluteDate<T> epochF;
  487.         switch (preambleField1 & 0x70) {
  488.             case 0x10:
  489.                 // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  490.                 epochF = ccsdsEpoch;
  491.                 break;
  492.             case 0x20:
  493.                 // the reference epoch is agency defined
  494.                 if (agencyDefinedEpoch == null) {
  495.                     throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  496.                 }
  497.                 epochF = agencyDefinedEpoch;
  498.                 break;
  499.             default :
  500.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  501.                                           formatByte(preambleField1));
  502.         }

  503.         // time field lengths
  504.         int coarseTimeLength = 1 + ((preambleField1 & 0x0C) >>> 2);
  505.         int fineTimeLength   = preambleField1 & 0x03;

  506.         if ((preambleField1 & 0x80) != 0x0) {
  507.             // there is an additional octet in preamble field
  508.             coarseTimeLength += (preambleField2 & 0x60) >>> 5;
  509.             fineTimeLength   += (preambleField2 & 0x1C) >>> 2;
  510.         }

  511.         if (timeField.length != coarseTimeLength + fineTimeLength) {
  512.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  513.                                       timeField.length, coarseTimeLength + fineTimeLength);
  514.         }

  515.         T seconds = field.getZero();
  516.         for (int i = 0; i < coarseTimeLength; ++i) {
  517.             seconds = seconds.multiply(256).add(field.getZero().add(toUnsigned(timeField[i])));
  518.         }
  519.         T subseconds = field.getZero();
  520.         for (int i = timeField.length - 1; i >= coarseTimeLength; --i) {
  521.             subseconds = (subseconds.add(toUnsigned(timeField[i]))).divide(256);
  522.         }
  523.         return new FieldAbsoluteDate<>(epochF, seconds).shiftedBy(subseconds);

  524.     }

  525.     /** Build an instance from a CCSDS Day Segmented Time Code (CDS).
  526.      * <p>
  527.      * CCSDS Day Segmented Time Code is defined in the blue book:
  528.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  529.      * </p>
  530.      *
  531.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  532.      *
  533.      * @param field field for the components
  534.      * @param preambleField field specifying the format, often not transmitted in
  535.      * data interfaces, as it is constant for a given data interface
  536.      * @param timeField byte array containing the time code
  537.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  538.      * specifies the {@link #getCCSDSEpoch(Field) CCSDS reference epoch} is used (and hence
  539.      * may be null in this case)
  540.      * @return an instance corresponding to the specified date
  541.      * @param <T> the type of the field elements
  542.      * @see #parseCCSDSDaySegmentedTimeCode(Field, byte, byte[], DateComponents,
  543.      * TimeScale)
  544.      */
  545.     @DefaultDataContext
  546.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> parseCCSDSDaySegmentedTimeCode(final Field<T> field,
  547.                                                                                                           final byte preambleField, final byte[] timeField,
  548.                                                                                                           final DateComponents agencyDefinedEpoch) {
  549.         return parseCCSDSDaySegmentedTimeCode(field, preambleField, timeField,
  550.                                               agencyDefinedEpoch, DataContext.getDefault().getTimeScales().getUTC());
  551.     }

  552.     /**
  553.      * Build an instance from a CCSDS Day Segmented Time Code (CDS).
  554.      * <p>
  555.      * CCSDS Day Segmented Time Code is defined in the blue book: CCSDS Time Code Format
  556.      * (CCSDS 301.0-B-4) published in November 2010
  557.      * </p>
  558.      *
  559.      * @param <T>                the type of the field elements
  560.      * @param field              field for the components
  561.      * @param preambleField      field specifying the format, often not transmitted in
  562.      *                           data interfaces, as it is constant for a given data
  563.      *                           interface
  564.      * @param timeField          byte array containing the time code
  565.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field specifies
  566.      *                           the {@link #getCCSDSEpoch(Field) CCSDS reference epoch}
  567.      *                           is used (and hence may be null in this case)
  568.      * @param utc                time scale used to compute date and time components.
  569.      * @return an instance corresponding to the specified date
  570.      * @since 10.1
  571.      */
  572.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> parseCCSDSDaySegmentedTimeCode(
  573.                                                                                                           final Field<T> field,
  574.                                                                                                           final byte preambleField,
  575.                                                                                                           final byte[] timeField,
  576.                                                                                                           final DateComponents agencyDefinedEpoch,
  577.                                                                                                           final TimeScale utc) {

  578.         // time code identification
  579.         if ((preambleField & 0xF0) != 0x40) {
  580.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  581.                                       formatByte(preambleField));
  582.         }

  583.         // reference epoch
  584.         final DateComponents epochDC;
  585.         if ((preambleField & 0x08) == 0x00) {
  586.             // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  587.             epochDC = DateComponents.CCSDS_EPOCH;
  588.         } else {
  589.             // the reference epoch is agency defined
  590.             if (agencyDefinedEpoch == null) {
  591.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  592.             }
  593.             epochDC = agencyDefinedEpoch;
  594.         }

  595.         // time field lengths
  596.         final int daySegmentLength = ((preambleField & 0x04) == 0x0) ? 2 : 3;
  597.         final int subMillisecondLength = (preambleField & 0x03) << 1;
  598.         if (subMillisecondLength == 6) {
  599.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  600.                                       formatByte(preambleField));
  601.         }
  602.         if (timeField.length != daySegmentLength + 4 + subMillisecondLength) {
  603.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  604.                                       timeField.length, daySegmentLength + 4 + subMillisecondLength);
  605.         }


  606.         int i   = 0;
  607.         int day = 0;
  608.         while (i < daySegmentLength) {
  609.             day = day * 256 + toUnsigned(timeField[i++]);
  610.         }

  611.         long milliInDay = 0l;
  612.         while (i < daySegmentLength + 4) {
  613.             milliInDay = milliInDay * 256 + toUnsigned(timeField[i++]);
  614.         }
  615.         final int milli   = (int) (milliInDay % 1000l);
  616.         final int seconds = (int) ((milliInDay - milli) / 1000l);

  617.         double subMilli = 0;
  618.         double divisor  = 1;
  619.         while (i < timeField.length) {
  620.             subMilli = subMilli * 256 + toUnsigned(timeField[i++]);
  621.             divisor *= 1000;
  622.         }

  623.         final DateComponents date = new DateComponents(epochDC, day);
  624.         final TimeComponents time = new TimeComponents(seconds);
  625.         return new FieldAbsoluteDate<>(field, date, time, utc).shiftedBy(milli * 1.0e-3 + subMilli / divisor);

  626.     }

  627.     /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  628.      * <p>
  629.      * CCSDS Calendar Segmented Time Code is defined in the blue book:
  630.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  631.      * </p>
  632.      *
  633.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  634.      *
  635.      * @param preambleField field specifying the format, often not transmitted in
  636.      * data interfaces, as it is constant for a given data interface
  637.      * @param timeField byte array containing the time code
  638.      * @return an instance corresponding to the specified date
  639.      * @see #parseCCSDSCalendarSegmentedTimeCode(byte, byte[], TimeScale)
  640.      */
  641.     @DefaultDataContext
  642.     public FieldAbsoluteDate<T> parseCCSDSCalendarSegmentedTimeCode(final byte preambleField, final byte[] timeField) {
  643.         return parseCCSDSCalendarSegmentedTimeCode(preambleField, timeField,
  644.                                                    DataContext.getDefault().getTimeScales().getUTC());
  645.     }

  646.     /**
  647.      * Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  648.      * <p>
  649.      * CCSDS Calendar Segmented Time Code is defined in the blue book: CCSDS Time Code
  650.      * Format (CCSDS 301.0-B-4) published in November 2010
  651.      * </p>
  652.      *
  653.      * @param preambleField field specifying the format, often not transmitted in data
  654.      *                      interfaces, as it is constant for a given data interface
  655.      * @param timeField     byte array containing the time code
  656.      * @param utc           time scale used to compute date and time components.
  657.      * @return an instance corresponding to the specified date
  658.      * @since 10.1
  659.      */
  660.     public FieldAbsoluteDate<T> parseCCSDSCalendarSegmentedTimeCode(
  661.                                                                     final byte preambleField,
  662.                                                                     final byte[] timeField,
  663.                                                                     final TimeScale utc) {

  664.         // time code identification
  665.         if ((preambleField & 0xF0) != 0x50) {
  666.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  667.                                       formatByte(preambleField));
  668.         }

  669.         // time field length
  670.         final int length = 7 + (preambleField & 0x07);
  671.         if (length == 14) {
  672.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  673.                                       formatByte(preambleField));
  674.         }
  675.         if (timeField.length != length) {
  676.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  677.                                       timeField.length, length);
  678.         }

  679.         // date part in the first four bytes
  680.         final DateComponents date;
  681.         if ((preambleField & 0x08) == 0x00) {
  682.             // month of year and day of month variation
  683.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  684.                                       toUnsigned(timeField[2]),
  685.                                       toUnsigned(timeField[3]));
  686.         } else {
  687.             // day of year variation
  688.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  689.                                       toUnsigned(timeField[2]) * 256 + toUnsigned(timeField[3]));
  690.         }

  691.         // time part from bytes 5 to last (between 7 and 13 depending on precision)
  692.         final TimeComponents time = new TimeComponents(toUnsigned(timeField[4]),
  693.                                                        toUnsigned(timeField[5]),
  694.                                                        toUnsigned(timeField[6]));
  695.         double subSecond = 0;
  696.         double divisor   = 1;
  697.         for (int i = 7; i < length; ++i) {
  698.             subSecond = subSecond * 100 + toUnsigned(timeField[i]);
  699.             divisor *= 100;
  700.         }

  701.         return new FieldAbsoluteDate<>(field, date, time, utc).shiftedBy(subSecond / divisor);

  702.     }

  703.     /** Decode a signed byte as an unsigned int value.
  704.      * @param b byte to decode
  705.      * @return an unsigned int value
  706.      */
  707.     private static int toUnsigned(final byte b) {
  708.         final int i = (int) b;
  709.         return (i < 0) ? 256 + i : i;
  710.     }

  711.     /** Format a byte as an hex string for error messages.
  712.      * @param data byte to format
  713.      * @return a formatted string
  714.      */
  715.     private static String formatByte(final byte data) {
  716.         return "0x" + Integer.toHexString(data).toUpperCase();
  717.     }

  718.     /** Build an instance corresponding to a Julian Day date.
  719.      * @param jd Julian day
  720.      * @param secondsSinceNoon seconds in the Julian day
  721.      * (BEWARE, Julian days start at noon, so 0.0 is noon)
  722.      * @param timeScale time scale in which the seconds in day are defined
  723.      * @return a new instant
  724.      * @param <T> the type of the field elements
  725.      */
  726.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createJDDate(final int jd, final T secondsSinceNoon,
  727.                                                                                         final TimeScale timeScale) {
  728.         return new FieldAbsoluteDate<>(secondsSinceNoon.getField(), new DateComponents(DateComponents.JULIAN_EPOCH, jd),
  729.                         TimeComponents.H12, timeScale).shiftedBy(secondsSinceNoon);
  730.     }

  731.     /** Build an instance corresponding to a Modified Julian Day date.
  732.      * @param mjd modified Julian day
  733.      * @param secondsInDay seconds in the day
  734.      * @param timeScale time scale in which the seconds in day are defined
  735.      * @return a new instant
  736.      * @param <T> the type of the field elements
  737.      */
  738.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createMJDDate(final int mjd, final T secondsInDay,
  739.                                                                                          final TimeScale timeScale) {
  740.         return new FieldAbsoluteDate<>(secondsInDay.getField(),
  741.                         new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, mjd),
  742.                         TimeComponents.H00,
  743.                         timeScale).shiftedBy(secondsInDay);
  744.     }

  745.     /** Build an instance corresponding to a GPS date.
  746.      *
  747.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  748.      *
  749.      * <p>GPS dates are provided as a week number starting at
  750.      * {@link #getGPSEpoch(Field) GPS epoch} and as a number of milliseconds
  751.      * since week start.</p>
  752.      * @param weekNumber week number since {@link #getGPSEpoch(Field) GPS epoch}
  753.      * @param milliInWeek number of milliseconds since week start
  754.      * @return a new instant
  755.      * @param <T> the type of the field elements
  756.      * @see #createGPSDate(int, CalculusFieldElement, TimeScale)
  757.      */
  758.     @DefaultDataContext
  759.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createGPSDate(final int weekNumber, final T milliInWeek) {
  760.         return createGPSDate(weekNumber, milliInWeek,
  761.                              DataContext.getDefault().getTimeScales().getGPS());
  762.     }

  763.     /**
  764.      * Build an instance corresponding to a GPS date.
  765.      * <p>GPS dates are provided as a week number starting at
  766.      * {@link #getGPSEpoch(Field) GPS epoch} and as a number of milliseconds since week
  767.      * start.</p>
  768.      *
  769.      * @param <T>         the type of the field elements
  770.      * @param weekNumber  week number since {@link #getGPSEpoch(Field) GPS epoch}
  771.      * @param milliInWeek number of milliseconds since week start
  772.      * @param gps         GPS time scale.
  773.      * @return a new instant
  774.      * @since 10.1
  775.      */
  776.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createGPSDate(
  777.                                                                                          final int weekNumber,
  778.                                                                                          final T milliInWeek,
  779.                                                                                          final TimeScale gps) {

  780.         final int day = (int) FastMath.floor(milliInWeek.getReal() / (1000.0 * Constants.JULIAN_DAY));
  781.         final T secondsInDay = milliInWeek.divide(1000.0).subtract(day * Constants.JULIAN_DAY);
  782.         return new FieldAbsoluteDate<>(milliInWeek.getField(), new DateComponents(DateComponents.GPS_EPOCH, weekNumber * 7 + day),
  783.                         TimeComponents.H00, gps).shiftedBy(secondsInDay);
  784.     }

  785.     /** Build an instance corresponding to a Julian Epoch (JE).
  786.      * <p>According to Lieske paper: <a
  787.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&amp;defaultprint=YES&amp;filetype=.pdf.">
  788.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
  789.      * vol. 73, no. 3, Mar. 1979, p. 282-284, Julian Epoch is related to Julian Ephemeris Date as:
  790.      * <pre>JE = 2000.0 + (JED - 2451545.0) / 365.25</pre>
  791.      * <p>This method reverts the formula above and computes an {@code FieldAbsoluteDate<T>} from the Julian Epoch.
  792.      *
  793.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  794.      *
  795.      * @param <T> the type of the field elements
  796.      * @param julianEpoch Julian epoch, like 2000.0 for defining the classical reference J2000.0
  797.      * @return a new instant
  798.      * @see #getJ2000Epoch(Field)
  799.      * @see #createBesselianEpoch(CalculusFieldElement)
  800.      * @see #createJulianEpoch(CalculusFieldElement, TimeScales)
  801.      */
  802.     @DefaultDataContext
  803.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createJulianEpoch(final T julianEpoch) {
  804.         return createJulianEpoch(julianEpoch,
  805.                                  DataContext.getDefault().getTimeScales());
  806.     }

  807.     /**
  808.      * Build an instance corresponding to a Julian Epoch (JE).
  809.      * <p>According to Lieske paper: <a
  810.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&amp;defaultprint=YES&amp;filetype=.pdf.">
  811.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>,
  812.      * Astronomy and Astrophysics, vol. 73, no. 3, Mar. 1979, p. 282-284, Julian Epoch is
  813.      * related to Julian Ephemeris Date as:
  814.      * <pre>JE = 2000.0 + (JED - 2451545.0) / 365.25</pre>
  815.      * <p>This method reverts the formula above and computes an {@code
  816.      * FieldAbsoluteDate<T>} from the Julian Epoch.
  817.      *
  818.      * @param <T>         the type of the field elements
  819.      * @param julianEpoch Julian epoch, like 2000.0 for defining the classical reference
  820.      *                    J2000.0
  821.      * @param timeScales  used in the computation.
  822.      * @return a new instant
  823.      * @see #getJ2000Epoch(Field)
  824.      * @see #createBesselianEpoch(CalculusFieldElement)
  825.      * @see TimeScales#createJulianEpoch(double)
  826.      * @since 10.1
  827.      */
  828.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createJulianEpoch(
  829.                                                                                              final T julianEpoch,
  830.                                                                                              final TimeScales timeScales) {

  831.         final Field<T> field = julianEpoch.getField();
  832.         return new FieldAbsoluteDate<>(new FieldAbsoluteDate<>(field, timeScales.getJ2000Epoch()),
  833.                         julianEpoch.subtract(2000.0).multiply(Constants.JULIAN_YEAR));
  834.     }

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

  860.     /**
  861.      * Build an instance corresponding to a Besselian Epoch (BE).
  862.      * <p>According to Lieske paper: <a
  863.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&amp;defaultprint=YES&amp;filetype=.pdf.">
  864.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>,
  865.      * Astronomy and Astrophysics, vol. 73, no. 3, Mar. 1979, p. 282-284, Besselian Epoch
  866.      * is related to Julian Ephemeris Date as:</p>
  867.      * <pre>
  868.      * BE = 1900.0 + (JED - 2415020.31352) / 365.242198781
  869.      * </pre>
  870.      * <p>
  871.      * This method reverts the formula above and computes an {@code FieldAbsoluteDate<T>}
  872.      * from the Besselian Epoch.
  873.      * </p>
  874.      *
  875.      * @param <T>            the type of the field elements
  876.      * @param besselianEpoch Besselian epoch, like 1950 for defining the classical
  877.      *                       reference B1950.0
  878.      * @param timeScales     used in the computation.
  879.      * @return a new instant
  880.      * @see #createJulianEpoch(CalculusFieldElement)
  881.      * @see TimeScales#createBesselianEpoch(double)
  882.      * @since 10.1
  883.      */
  884.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createBesselianEpoch(
  885.                                                                                                 final T besselianEpoch,
  886.                                                                                                 final TimeScales timeScales) {

  887.         final Field<T> field = besselianEpoch.getField();
  888.         return new FieldAbsoluteDate<>(new FieldAbsoluteDate<>(field, timeScales.getJ2000Epoch()),
  889.                         besselianEpoch.subtract(1900).multiply(Constants.BESSELIAN_YEAR).add(
  890.                                                                                              Constants.JULIAN_DAY * (-36525) + Constants.JULIAN_DAY * 0.31352));
  891.     }

  892.     /** Reference epoch for julian dates: -4712-01-01T12:00:00 Terrestrial Time.
  893.      * <p>Both <code>java.util.Date</code> and {@link DateComponents} classes
  894.      * follow the astronomical conventions and consider a year 0 between
  895.      * years -1 and +1, hence this reference date lies in year -4712 and not
  896.      * in year -4713 as can be seen in other documents or programs that obey
  897.      * a different convention (for example the <code>convcal</code> utility).</p>
  898.      *
  899.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  900.      *
  901.      * @param <T> the type of the field elements
  902.      * @param field field for the components
  903.      * @return the reference epoch for julian dates as a FieldAbsoluteDate
  904.      * @see AbsoluteDate#JULIAN_EPOCH
  905.      * @see TimeScales#getJulianEpoch()
  906.      */
  907.     @DefaultDataContext
  908.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getJulianEpoch(final Field<T> field) {
  909.         return new FieldAbsoluteDate<>(field,
  910.                         DataContext.getDefault().getTimeScales().getJulianEpoch());
  911.     }

  912.     /** Reference epoch for modified julian dates: 1858-11-17T00:00:00 Terrestrial Time.
  913.      *
  914.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  915.      *
  916.      * @param <T> the type of the field elements
  917.      * @param field field for the components
  918.      * @return the reference epoch for modified julian dates as a FieldAbsoluteDate
  919.      * @see AbsoluteDate#MODIFIED_JULIAN_EPOCH
  920.      * @see TimeScales#getModifiedJulianEpoch()
  921.      */
  922.     @DefaultDataContext
  923.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getModifiedJulianEpoch(final Field<T> field) {
  924.         return new FieldAbsoluteDate<>(field,
  925.                         DataContext.getDefault().getTimeScales().getModifiedJulianEpoch());
  926.     }

  927.     /** Reference epoch for 1950 dates: 1950-01-01T00:00:00 Terrestrial Time.
  928.      *
  929.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  930.      *
  931.      * @param <T> the type of the field elements
  932.      * @param field field for the components
  933.      * @return the reference epoch for 1950 dates as a FieldAbsoluteDate
  934.      * @see AbsoluteDate#FIFTIES_EPOCH
  935.      * @see TimeScales#getFiftiesEpoch()
  936.      */
  937.     @DefaultDataContext
  938.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getFiftiesEpoch(final Field<T> field) {
  939.         return new FieldAbsoluteDate<>(field,
  940.                         DataContext.getDefault().getTimeScales().getFiftiesEpoch());
  941.     }

  942.     /** Reference epoch for CCSDS Time Code Format (CCSDS 301.0-B-4):
  943.      *
  944.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  945.      *
  946.      * 1958-01-01T00:00:00 International Atomic Time (<em>not</em> UTC).
  947.      * @param <T> the type of the field elements
  948.      * @param field field for the components
  949.      * @return the reference epoch for CCSDS Time Code Format as a FieldAbsoluteDate
  950.      * @see AbsoluteDate#CCSDS_EPOCH
  951.      * @see TimeScales#getCcsdsEpoch()
  952.      */
  953.     @DefaultDataContext
  954.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getCCSDSEpoch(final Field<T> field) {
  955.         return new FieldAbsoluteDate<>(field,
  956.                         DataContext.getDefault().getTimeScales().getCcsdsEpoch());
  957.     }

  958.     /** Reference epoch for Galileo System Time: 1999-08-22T00:00:00 UTC.
  959.      *
  960.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  961.      *
  962.      * @param <T> the type of the field elements
  963.      * @param field field for the components
  964.      * @return the reference epoch for Galileo System Time as a FieldAbsoluteDate
  965.      * @see AbsoluteDate#GALILEO_EPOCH
  966.      * @see TimeScales#getGalileoEpoch()
  967.      */
  968.     @DefaultDataContext
  969.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getGalileoEpoch(final Field<T> field) {
  970.         return new FieldAbsoluteDate<>(field,
  971.                         DataContext.getDefault().getTimeScales().getGalileoEpoch());
  972.     }

  973.     /** Reference epoch for GPS weeks: 1980-01-06T00:00:00 GPS time.
  974.      *
  975.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  976.      *
  977.      * @param <T> the type of the field elements
  978.      * @param field field for the components
  979.      * @return the reference epoch for GPS weeks as a FieldAbsoluteDate
  980.      * @see AbsoluteDate#GPS_EPOCH
  981.      * @see TimeScales#getGpsEpoch()
  982.      */
  983.     @DefaultDataContext
  984.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getGPSEpoch(final Field<T> field) {
  985.         return new FieldAbsoluteDate<>(field,
  986.                         DataContext.getDefault().getTimeScales().getGpsEpoch());
  987.     }

  988.     /** J2000.0 Reference epoch: 2000-01-01T12:00:00 Terrestrial Time (<em>not</em> UTC).
  989.      *
  990.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  991.      *
  992.      * @param <T> the type of the field elements
  993.      * @param field field for the components
  994.      * @return the J2000.0 reference epoch as a FieldAbsoluteDate
  995.      * @see #createJulianEpoch(CalculusFieldElement)
  996.      * @see AbsoluteDate#J2000_EPOCH
  997.      * @see TimeScales#getJ2000Epoch()
  998.      */
  999.     @DefaultDataContext
  1000.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getJ2000Epoch(final Field<T> field) {
  1001.         return new FieldAbsoluteDate<>(field,
  1002.                         DataContext.getDefault().getTimeScales().getJ2000Epoch());
  1003.     }

  1004.     /** Java Reference epoch: 1970-01-01T00:00:00 Universal Time Coordinate.
  1005.      *
  1006.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1007.      *
  1008.      * <p>
  1009.      * Between 1968-02-01 and 1972-01-01, UTC-TAI = 4.213 170 0s + (MJD - 39 126) x 0.002 592s.
  1010.      * As on 1970-01-01 MJD = 40587, UTC-TAI = 8.000082s
  1011.      * </p>
  1012.      * @param <T> the type of the field elements
  1013.      * @param field field for the components
  1014.      * @return the Java reference epoch as a FieldAbsoluteDate
  1015.      * @see AbsoluteDate#JAVA_EPOCH
  1016.      * @see TimeScales#getJavaEpoch()
  1017.      */
  1018.     @DefaultDataContext
  1019.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getJavaEpoch(final Field<T> field) {
  1020.         return new FieldAbsoluteDate<>(field,
  1021.                         DataContext.getDefault().getTimeScales().getJavaEpoch());
  1022.     }

  1023.     /** Dummy date at infinity in the past direction.
  1024.      * @param <T> the type of the field elements
  1025.      * @param field field for the components
  1026.      * @return a dummy date at infinity in the past direction as a FieldAbsoluteDate
  1027.      * @see AbsoluteDate#PAST_INFINITY
  1028.      * @see TimeScales#getPastInfinity()
  1029.      */
  1030.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getPastInfinity(final Field<T> field) {
  1031.         return new FieldAbsoluteDate<>(field, AbsoluteDate.PAST_INFINITY);
  1032.     }

  1033.     /** Dummy date at infinity in the future direction.
  1034.      * @param <T> the type of the field elements
  1035.      * @param field field for the components
  1036.      * @return a dummy date at infinity in the future direction as a FieldAbsoluteDate
  1037.      * @see AbsoluteDate#FUTURE_INFINITY
  1038.      * @see TimeScales#getFutureInfinity()
  1039.      */
  1040.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getFutureInfinity(final Field<T> field) {
  1041.         return new FieldAbsoluteDate<>(field, AbsoluteDate.FUTURE_INFINITY);
  1042.     }

  1043.     /**
  1044.      * Get an arbitrary date. Useful when a non-null date is needed but its values does
  1045.      * not matter.
  1046.      *
  1047.      * @param <T>   the type of the field elements
  1048.      * @param field field for the components
  1049.      * @return an arbitrary date.
  1050.      */
  1051.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getArbitraryEpoch(final Field<T> field) {

  1052.         return new FieldAbsoluteDate<>(field, AbsoluteDate.ARBITRARY_EPOCH);
  1053.     }


  1054.     /** Get a time-shifted date.
  1055.      * <p>
  1056.      * Calling this method is equivalent to call {@code new FieldAbsoluteDate&lt;&gt;(this, dt)}.
  1057.      * </p>
  1058.      * @param dt time shift in seconds
  1059.      * @return a new date, shifted with respect to instance (which is immutable)
  1060.      * @see org.orekit.utils.FieldPVCoordinates#shiftedBy(double)
  1061.      * @see org.orekit.attitudes.FieldAttitude#shiftedBy(double)
  1062.      * @see org.orekit.orbits.FieldOrbit#shiftedBy(double)
  1063.      * @see org.orekit.propagation.FieldSpacecraftState#shiftedBy(double)
  1064.      */
  1065.     @Override
  1066.     public FieldAbsoluteDate<T> shiftedBy(final T dt) {
  1067.         return new FieldAbsoluteDate<>(this, dt);
  1068.     }

  1069.     /** Compute the physically elapsed duration between two instants.
  1070.      * <p>The returned duration is the number of seconds physically
  1071.      * elapsed between the two instants, measured in a regular time
  1072.      * scale with respect to surface of the Earth (i.e either the {@link
  1073.      * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
  1074.      * GPSScale GPS scale}). It is the only method that gives a
  1075.      * duration with a physical meaning.</p>
  1076.      * <p>This method gives the same result (with less computation)
  1077.      * as calling {@link #offsetFrom(FieldAbsoluteDate, TimeScale)}
  1078.      * with a second argument set to one of the regular scales cited
  1079.      * above.</p>
  1080.      * <p>This method is the reverse of the {@link #FieldAbsoluteDate(FieldAbsoluteDate,
  1081.      * double)} constructor.</p>
  1082.      * @param instant instant to subtract from the instance
  1083.      * @return offset in seconds between the two instants (positive
  1084.      * if the instance is posterior to the argument)
  1085.      * @see #offsetFrom(FieldAbsoluteDate, TimeScale)
  1086.      * @see #FieldAbsoluteDate(FieldAbsoluteDate, double)
  1087.      */
  1088.     public T durationFrom(final FieldAbsoluteDate<T> instant) {
  1089.         return offset.subtract(instant.offset).add(epoch - instant.epoch);
  1090.     }

  1091.     /** Compute the physically elapsed duration between two instants.
  1092.      * <p>The returned duration is the number of seconds physically
  1093.      * elapsed between the two instants, measured in a regular time
  1094.      * scale with respect to surface of the Earth (i.e either the {@link
  1095.      * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
  1096.      * GPSScale GPS scale}). It is the only method that gives a
  1097.      * duration with a physical meaning.</p>
  1098.      * <p>This method gives the same result (with less computation)
  1099.      * as calling {@link #offsetFrom(FieldAbsoluteDate, TimeScale)}
  1100.      * with a second argument set to one of the regular scales cited
  1101.      * above.</p>
  1102.      * <p>This method is the reverse of the {@link #FieldAbsoluteDate(FieldAbsoluteDate,
  1103.      * double)} constructor.</p>
  1104.      * @param instant instant to subtract from the instance
  1105.      * @return offset in seconds between the two instants (positive
  1106.      * if the instance is posterior to the argument)
  1107.      * @see #offsetFrom(FieldAbsoluteDate, TimeScale)
  1108.      * @see #FieldAbsoluteDate(FieldAbsoluteDate, double)
  1109.      */
  1110.     public T durationFrom(final AbsoluteDate instant) {
  1111.         return offset.subtract(instant.getOffset()).add(epoch - instant.getEpoch());
  1112.     }

  1113.     /** Compute the apparent clock offset between two instant <em>in the
  1114.      * perspective of a specific {@link TimeScale time scale}</em>.
  1115.      * <p>The offset is the number of seconds counted in the given
  1116.      * time scale between the locations of the two instants, with
  1117.      * all time scale irregularities removed (i.e. considering all
  1118.      * days are exactly 86400 seconds long). This method will give
  1119.      * a result that may not have a physical meaning if the time scale
  1120.      * is irregular. For example since a leap second was introduced at
  1121.      * the end of 2005, the apparent offset between 2005-12-31T23:59:59
  1122.      * and 2006-01-01T00:00:00 is 1 second, but the physical duration
  1123.      * of the corresponding time interval as returned by the {@link
  1124.      * #durationFrom(FieldAbsoluteDate)} method is 2 seconds.</p>
  1125.      * <p>This method is the reverse of the {@link #FieldAbsoluteDate(FieldAbsoluteDate,
  1126.      * double, TimeScale)} constructor.</p>
  1127.      * @param instant instant to subtract from the instance
  1128.      * @param timeScale time scale with respect to which the offset should
  1129.      * be computed
  1130.      * @return apparent clock offset in seconds between the two instants
  1131.      * (positive if the instance is posterior to the argument)
  1132.      * @see #durationFrom(FieldAbsoluteDate)
  1133.      * @see #FieldAbsoluteDate(FieldAbsoluteDate, double, TimeScale)
  1134.      */
  1135.     public T offsetFrom(final FieldAbsoluteDate<T> instant, final TimeScale timeScale) {
  1136.         final long   elapsedDurationA = epoch - instant.epoch;
  1137.         final T elapsedDurationB = offset.add(timeScale.offsetFromTAI(this)).
  1138.                         subtract(instant.offset.add(timeScale.offsetFromTAI(instant)));
  1139.         return  elapsedDurationB.add(elapsedDurationA);
  1140.     }

  1141.     /** Compute the offset between two time scales at the current instant.
  1142.      * <p>The offset is defined as <i>l₁-l₂</i>
  1143.      * where <i>l₁</i> is the location of the instant in
  1144.      * the <code>scale1</code> time scale and <i>l₂</i> is the
  1145.      * location of the instant in the <code>scale2</code> time scale.</p>
  1146.      * @param scale1 first time scale
  1147.      * @param scale2 second time scale
  1148.      * @return offset in seconds between the two time scales at the
  1149.      * current instant
  1150.      */
  1151.     public T timeScalesOffset(final TimeScale scale1, final TimeScale scale2) {
  1152.         return scale1.offsetFromTAI(this).subtract(scale2.offsetFromTAI(this));
  1153.     }

  1154.     /** Convert the instance to a Java {@link java.util.Date Date}.
  1155.      * <p>Conversion to the Date class induces a loss of precision because
  1156.      * the Date class does not provide sub-millisecond information. Java Dates
  1157.      * are considered to be locations in some times scales.</p>
  1158.      * @param timeScale time scale to use
  1159.      * @return a {@link java.util.Date Date} instance representing the location
  1160.      * of the instant in the time scale
  1161.      */
  1162.     public Date toDate(final TimeScale timeScale) {
  1163.         final double time = epoch + (offset.getReal() + timeScale.offsetFromTAI(this).getReal());
  1164.         return new Date(FastMath.round((time + 10957.5 * 86400.0) * 1000));
  1165.     }

  1166.     /** Split the instance into date/time components.
  1167.      * @param timeScale time scale to use
  1168.      * @return date/time components
  1169.      */
  1170.     public DateTimeComponents getComponents(final TimeScale timeScale) {

  1171.         if (Double.isInfinite(offset.getReal())) {
  1172.             // special handling for past and future infinity
  1173.             if (offset.getReal() < 0) {
  1174.                 return new DateTimeComponents(DateComponents.MIN_EPOCH, TimeComponents.H00);
  1175.             } else {
  1176.                 return new DateTimeComponents(DateComponents.MAX_EPOCH,
  1177.                                               new TimeComponents(23, 59, 59.999));
  1178.             }
  1179.         }

  1180.         // Compute offset from 2000-01-01T00:00:00 in specified time scale.
  1181.         // Use 2Sum for high accuracy.
  1182.         final double taiOffset = timeScale.offsetFromTAI(this).getReal();
  1183.         final SumAndResidual sumAndResidual = MathUtils.twoSum(offset.getReal(), taiOffset);

  1184.         // split date and time
  1185.         final long   carry = (long) FastMath.floor(sumAndResidual.getSum());
  1186.         double offset2000B = (sumAndResidual.getSum() - carry) + sumAndResidual.getResidual();
  1187.         long   offset2000A = epoch + carry + 43200l;
  1188.         if (offset2000B < 0) {
  1189.             offset2000A -= 1;
  1190.             offset2000B += 1;
  1191.         }
  1192.         long time = offset2000A % 86400l;
  1193.         if (time < 0l) {
  1194.             time += 86400l;
  1195.         }
  1196.         final int date = (int) ((offset2000A - time) / 86400l);

  1197.         // extract calendar elements
  1198.         final DateComponents dateComponents = new DateComponents(DateComponents.J2000_EPOCH, date);
  1199.         // extract time element, accounting for leap seconds
  1200.         final double leap = timeScale.insideLeap(this) ? timeScale.getLeap(this.toAbsoluteDate()) : 0;
  1201.         final int minuteDuration = timeScale.minuteDuration(this);
  1202.         final TimeComponents timeComponents = TimeComponents.fromSeconds((int) time, offset2000B, leap, minuteDuration);

  1203.         // build the components
  1204.         return new DateTimeComponents(dateComponents, timeComponents);

  1205.     }

  1206.     /** Split the instance into date/time components for a local time.
  1207.      *
  1208.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1209.      *
  1210.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1211.      * negative Westward UTC)
  1212.      * @return date/time components
  1213.      * @see #getComponents(int, TimeScale)
  1214.      */
  1215.     @DefaultDataContext
  1216.     public DateTimeComponents getComponents(final int minutesFromUTC) {
  1217.         return getComponents(minutesFromUTC,
  1218.                              DataContext.getDefault().getTimeScales().getUTC());
  1219.     }

  1220.     /**
  1221.      * Split the instance into date/time components for a local time.
  1222.      *
  1223.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1224.      *                       negative Westward UTC)
  1225.      * @param utc            time scale used to compute date and time components.
  1226.      * @return date/time components
  1227.      * @since 10.1
  1228.      */
  1229.     public DateTimeComponents getComponents(final int minutesFromUTC,
  1230.                                             final TimeScale utc) {

  1231.         final DateTimeComponents utcComponents = getComponents(utc);

  1232.         // shift the date according to UTC offset, but WITHOUT touching the seconds,
  1233.         // as they may exceed 60.0 during a leap seconds introduction,
  1234.         // and we want to preserve these special cases
  1235.         final double seconds = utcComponents.getTime().getSecond();
  1236.         int minute = utcComponents.getTime().getMinute() + minutesFromUTC;
  1237.         final int hourShift;
  1238.         if (minute < 0) {
  1239.             hourShift = (minute - 59) / 60;
  1240.         } else if (minute > 59) {
  1241.             hourShift = minute / 60;
  1242.         } else {
  1243.             hourShift = 0;
  1244.         }
  1245.         minute -= 60 * hourShift;
  1246.         int hour = utcComponents.getTime().getHour() + hourShift;
  1247.         final int dayShift;
  1248.         if (hour < 0) {
  1249.             dayShift = (hour - 23) / 24;
  1250.         } else if (hour > 23) {
  1251.             dayShift = hour / 24;
  1252.         } else {
  1253.             dayShift = 0;
  1254.         }
  1255.         hour -= 24 * dayShift;

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

  1258.     }

  1259.     /** {@inheritDoc} */
  1260.     @Override
  1261.     public FieldAbsoluteDate<T> getDate() {
  1262.         return this;
  1263.     }

  1264.     /** Get the field.
  1265.      * @return field instance.
  1266.      */
  1267.     public Field<T> getField() {
  1268.         return field;
  1269.     }

  1270.     /** Split the instance into date/time components for a time zone.
  1271.      *
  1272.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1273.      *
  1274.      * @param timeZone time zone
  1275.      * @return date/time components
  1276.      * @see #getComponents(TimeZone, TimeScale)
  1277.      */
  1278.     @DefaultDataContext
  1279.     public DateTimeComponents getComponents(final TimeZone timeZone) {
  1280.         return getComponents(timeZone, DataContext.getDefault().getTimeScales().getUTC());
  1281.     }

  1282.     /** Split the instance into date/time components for a time zone.
  1283.      * @param timeZone time zone
  1284.      * @param utc            time scale used to compute date and time components.
  1285.      * @return date/time components
  1286.      * @since 10.1
  1287.      */
  1288.     public DateTimeComponents getComponents(final TimeZone timeZone,
  1289.                                             final TimeScale utc) {
  1290.         final FieldAbsoluteDate<T> javaEpoch =
  1291.                         new FieldAbsoluteDate<>(field, DateComponents.JAVA_EPOCH, utc);
  1292.         final long milliseconds = FastMath.round((offsetFrom(javaEpoch, utc).getReal()) * 1000);
  1293.         return getComponents(timeZone.getOffset(milliseconds) / 60000, utc);
  1294.     }

  1295.     /** Compare the instance with another date.
  1296.      * @param date other date to compare the instance to
  1297.      * @return a negative integer, zero, or a positive integer as this date
  1298.      * is before, simultaneous, or after the specified date.
  1299.      */
  1300.     public int compareTo(final FieldAbsoluteDate<T> date) {
  1301.         return Double.compare(durationFrom(date).getReal(), 0.0);
  1302.     }


  1303.     /** Check if the instance represents the same time as another instance.
  1304.      * @param date other date
  1305.      * @return true if the instance and the other date refer to the same instant
  1306.      */
  1307.     @SuppressWarnings("unchecked")
  1308.     public boolean equals(final Object date) {

  1309.         if (date == this) {
  1310.             // first fast check
  1311.             return true;
  1312.         }

  1313.         if (date instanceof FieldAbsoluteDate) {
  1314.             return durationFrom((FieldAbsoluteDate<T>) date).getReal() == 0.0;
  1315.         }

  1316.         return false;

  1317.     }

  1318.     /** Check if the instance represents the same time as another.
  1319.      * @param other the instant to compare this date to
  1320.      * @return true if the instance and the argument refer to the same instant
  1321.      * @see #isCloseTo(FieldTimeStamped, double)
  1322.      * @since 10.1
  1323.      */
  1324.     public boolean isEqualTo(final FieldTimeStamped<T> other) {
  1325.         return this.equals(other.getDate());
  1326.     }

  1327.     /** Check if the instance time is close to another.
  1328.      * @param other the instant to compare this date to
  1329.      * @param tolerance the separation, in seconds, under which the two instants will be considered close to each other
  1330.      * @return true if the duration between the instance and the argument is strictly below the tolerance
  1331.      * @see #isEqualTo(FieldTimeStamped)
  1332.      * @since 10.1
  1333.      */
  1334.     public boolean isCloseTo(final FieldTimeStamped<T> other, final double tolerance) {
  1335.         return FastMath.abs(this.durationFrom(other.getDate()).getReal()) < tolerance;
  1336.     }

  1337.     /** Check if the instance represents a time that is strictly before another.
  1338.      * @param other the instant to compare this date to
  1339.      * @return true if the instance is strictly before the argument when ordering chronologically
  1340.      * @see #isBeforeOrEqualTo(FieldTimeStamped)
  1341.      * @since 10.1
  1342.      */
  1343.     public boolean isBefore(final FieldTimeStamped<T> other) {
  1344.         return this.compareTo(other.getDate()) < 0;
  1345.     }

  1346.     /** Check if the instance represents a time that is strictly after another.
  1347.      * @param other the instant to compare this date to
  1348.      * @return true if the instance is strictly after the argument when ordering chronologically
  1349.      * @see #isAfterOrEqualTo(FieldTimeStamped)
  1350.      * @since 10.1
  1351.      */
  1352.     public boolean isAfter(final FieldTimeStamped<T> other) {
  1353.         return this.compareTo(other.getDate()) > 0;
  1354.     }

  1355.     /** Check if the instance represents a time that is before or equal to another.
  1356.      * @param other the instant to compare this date to
  1357.      * @return true if the instance is before (or equal to) the argument when ordering chronologically
  1358.      * @see #isBefore(FieldTimeStamped)
  1359.      * @since 10.1
  1360.      */
  1361.     public boolean isBeforeOrEqualTo(final FieldTimeStamped<T> other) {
  1362.         return this.isEqualTo(other) || this.isBefore(other);
  1363.     }

  1364.     /** Check if the instance represents a time that is after or equal to another.
  1365.      * @param other the instant to compare this date to
  1366.      * @return true if the instance is after (or equal to) the argument when ordering chronologically
  1367.      * @see #isAfterOrEqualTo(FieldTimeStamped)
  1368.      * @since 10.1
  1369.      */
  1370.     public boolean isAfterOrEqualTo(final FieldTimeStamped<T> other) {
  1371.         return this.isEqualTo(other) || this.isAfter(other);
  1372.     }

  1373.     /** Check if the instance represents a time that is strictly between two others representing
  1374.      * the boundaries of a time span. The two boundaries can be provided in any order: in other words,
  1375.      * whether <code>boundary</code> represents a time that is before or after <code>otherBoundary</code> will
  1376.      * not change the result of this method.
  1377.      * @param boundary one end of the time span
  1378.      * @param otherBoundary the other end of the time span
  1379.      * @return true if the instance is strictly between the two arguments when ordering chronologically
  1380.      * @see #isBetweenOrEqualTo(FieldTimeStamped, FieldTimeStamped)
  1381.      * @since 10.1
  1382.      */
  1383.     public boolean isBetween(final FieldTimeStamped<T> boundary, final FieldTimeStamped<T> otherBoundary) {
  1384.         final FieldTimeStamped<T> beginning;
  1385.         final FieldTimeStamped<T> end;
  1386.         if (boundary.getDate().isBefore(otherBoundary)) {
  1387.             beginning = boundary;
  1388.             end = otherBoundary;
  1389.         } else {
  1390.             beginning = otherBoundary;
  1391.             end = boundary;
  1392.         }
  1393.         return this.isAfter(beginning) && this.isBefore(end);
  1394.     }

  1395.     /** Check if the instance represents a time that is between two others representing
  1396.      * the boundaries of a time span, or equal to one of them. The two boundaries can be provided in any order:
  1397.      * in other words, whether <code>boundary</code> represents a time that is before or after
  1398.      * <code>otherBoundary</code> will not change the result of this method.
  1399.      * @param boundary one end of the time span
  1400.      * @param otherBoundary the other end of the time span
  1401.      * @return true if the instance is between the two arguments (or equal to at least one of them)
  1402.      * when ordering chronologically
  1403.      * @see #isBetween(FieldTimeStamped, FieldTimeStamped)
  1404.      * @since 10.1
  1405.      */
  1406.     public boolean isBetweenOrEqualTo(final FieldTimeStamped<T> boundary, final FieldTimeStamped<T> otherBoundary) {
  1407.         return this.isEqualTo(boundary) || this.isEqualTo(otherBoundary) || this.isBetween(boundary, otherBoundary);
  1408.     }

  1409.     /** Get a hashcode for this date.
  1410.      * @return hashcode
  1411.      */
  1412.     public int hashCode() {
  1413.         final long l = Double.doubleToLongBits(durationFrom(AbsoluteDate.ARBITRARY_EPOCH).getReal());
  1414.         return (int) (l ^ (l >>> 32));
  1415.     }

  1416.     /**
  1417.      * Get a String representation of the instant location with up to 16 digits of
  1418.      * precision for the seconds value.
  1419.      *
  1420.      * <p> Since this method is used in exception messages and error handling every
  1421.      * effort is made to return some representation of the instant. If UTC is available
  1422.      * from the default data context then it is used to format the string in UTC. If not
  1423.      * then TAI is used. Finally if the prior attempts fail this method falls back to
  1424.      * converting this class's internal representation to a string.
  1425.      *
  1426.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1427.      *
  1428.      * @return a string representation of the instance, in ISO-8601 format if UTC is
  1429.      * available from the default data context.
  1430.      * @see AbsoluteDate#toString()
  1431.      * @see #toString(TimeScale)
  1432.      * @see DateTimeComponents#toString(int, int)
  1433.      */
  1434.     @DefaultDataContext
  1435.     public String toString() {
  1436.         return toAbsoluteDate().toString();
  1437.     }

  1438.     /**
  1439.      * Get a String representation of the instant location in ISO-8601 format without the
  1440.      * UTC offset and with up to 16 digits of precision for the seconds value.
  1441.      *
  1442.      * @param timeScale time scale to use
  1443.      * @return a string representation of the instance.
  1444.      * @see DateTimeComponents#toString(int, int)
  1445.      */
  1446.     public String toString(final TimeScale timeScale) {
  1447.         return getComponents(timeScale).toStringWithoutUtcOffset();
  1448.     }

  1449.     /** Get a String representation of the instant location for a local time.
  1450.      *
  1451.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1452.      *
  1453.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1454.      * negative Westward UTC).
  1455.      * @return string representation of the instance,
  1456.      * in ISO-8601 format with milliseconds accuracy
  1457.      * @see #toString(int, TimeScale)
  1458.      */
  1459.     @DefaultDataContext
  1460.     public String toString(final int minutesFromUTC) {
  1461.         return toString(minutesFromUTC,
  1462.                         DataContext.getDefault().getTimeScales().getUTC());
  1463.     }

  1464.     /**
  1465.      * Get a String representation of the instant location for a local time.
  1466.      *
  1467.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1468.      *                       negative Westward UTC).
  1469.      * @param utc            time scale used to compute date and time components.
  1470.      * @return string representation of the instance, in ISO-8601 format with milliseconds
  1471.      * accuracy
  1472.      * @since 10.1
  1473.      */
  1474.     public String toString(final int minutesFromUTC, final TimeScale utc) {
  1475.         final int minuteDuration = utc.minuteDuration(this);
  1476.         return getComponents(minutesFromUTC, utc).toString(minuteDuration);
  1477.     }

  1478.     /** Get a String representation of the instant location for a time zone.
  1479.      *
  1480.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1481.      *
  1482.      * @param timeZone time zone
  1483.      * @return string representation of the instance,
  1484.      * in ISO-8601 format with milliseconds accuracy
  1485.      * @see #toString(TimeZone, TimeScale)
  1486.      */
  1487.     @DefaultDataContext
  1488.     public String toString(final TimeZone timeZone) {
  1489.         return toString(timeZone, DataContext.getDefault().getTimeScales().getUTC());
  1490.     }

  1491.     /**
  1492.      * Get a String representation of the instant location for a time zone.
  1493.      *
  1494.      * @param timeZone time zone
  1495.      * @param utc      time scale used to compute date and time components.
  1496.      * @return string representation of the instance, in ISO-8601 format with milliseconds
  1497.      * accuracy
  1498.      * @since 10.1
  1499.      */
  1500.     public String toString(final TimeZone timeZone, final TimeScale utc) {
  1501.         final int minuteDuration = utc.minuteDuration(this);
  1502.         return getComponents(timeZone, utc).toString(minuteDuration);
  1503.     }

  1504.     /** Get a time-shifted date.
  1505.      * <p>
  1506.      * Calling this method is equivalent to call <code>new FieldAbsoluteDate(this, dt)</code>.
  1507.      * </p>
  1508.      * @param dt time shift in seconds
  1509.      * @return a new date, shifted with respect to instance (which is immutable)
  1510.      * @see org.orekit.utils.FieldPVCoordinates#shiftedBy(double)
  1511.      * @see org.orekit.attitudes.FieldAttitude#shiftedBy(double)
  1512.      * @see org.orekit.orbits.FieldOrbit#shiftedBy(double)
  1513.      * @see org.orekit.propagation.FieldSpacecraftState#shiftedBy(double)
  1514.      */
  1515.     @Override
  1516.     public FieldAbsoluteDate<T> shiftedBy(final double dt) {
  1517.         return new FieldAbsoluteDate<>(this, dt);
  1518.     }


  1519.     /** Transform the FieldAbsoluteDate in an AbsoluteDate.
  1520.      * @return AbsoluteDate of the FieldObject
  1521.      * */
  1522.     public AbsoluteDate toAbsoluteDate() {
  1523.         return new AbsoluteDate(epoch, offset.getReal());
  1524.     }

  1525.     /** Check if the Field is semantically equal to zero.
  1526.      *
  1527.      * <p> Using {@link FieldElement#isZero()}
  1528.      *
  1529.      * @return true the Field is semantically equal to zero
  1530.      * @since 12.0
  1531.      */
  1532.     public boolean hasZeroField() {
  1533.         return (offset instanceof Derivative<?> || offset instanceof Complex) && offset.subtract(offset.getReal()).isZero();
  1534.     }
  1535. }