FieldAbsoluteDate.java

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

  18. import java.util.Date;
  19. import java.util.TimeZone;

  20. import org.hipparchus.Field;
  21. import org.hipparchus.CalculusFieldElement;
  22. import org.hipparchus.util.FastMath;
  23. import org.hipparchus.util.MathUtils;
  24. import org.hipparchus.util.MathUtils.FieldSumAndResidual;
  25. import org.hipparchus.util.MathUtils.SumAndResidual;
  26. import org.orekit.annotation.DefaultDataContext;
  27. import org.orekit.data.DataContext;
  28. import org.orekit.errors.OrekitException;
  29. import org.orekit.errors.OrekitMessages;
  30. import org.orekit.utils.Constants;

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

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

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

  103.     /** Offset from the reference epoch in seconds. */
  104.     private final  T offset;

  105.     /** Field used by default.*/
  106.     private Field<T> field;

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

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

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

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

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

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

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

  222.     }

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

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

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

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

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

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


  308.     /** Build an instance from an elapsed duration since to another instant.
  309.      * <p>It is important to note that the elapsed duration is <em>not</em>
  310.      * the difference between two readings on a time scale.
  311.      * @param since start instant of the measured duration
  312.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  313.      * instant, as measured in a regular time scale
  314.      */
  315.     public FieldAbsoluteDate(final FieldAbsoluteDate<T> since, final double elapsedDuration) {
  316.         this(since.epoch, elapsedDuration, since.offset);
  317.     }


  318.     /** Build an instance from an elapsed duration since to another instant.
  319.      * <p>It is important to note that the elapsed duration is <em>not</em>
  320.      * the difference between two readings on a time scale.
  321.      * @param since start instant of the measured duration
  322.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  323.      * instant, as measured in a regular time scale
  324.      */
  325.     public FieldAbsoluteDate(final AbsoluteDate since, final T elapsedDuration) {
  326.         this(since.getEpoch(), since.getOffset(), elapsedDuration);
  327.     }

  328.     /** Build an instance from an apparent clock offset with respect to another
  329.      * instant <em>in the perspective of a specific {@link TimeScale time scale}</em>.
  330.      * <p>It is important to note that the apparent clock offset <em>is</em> the
  331.      * difference between two readings on a time scale and <em>not</em> an elapsed
  332.      * duration. As an example, the apparent clock offset between the two instants
  333.      * leading to the readings 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the
  334.      * {@link UTCScale UTC} time scale is 1 second, but the elapsed duration is 2
  335.      * seconds because a leap second has been introduced at the end of 2005 in this
  336.      * time scale.</p>
  337.      * <p>This constructor is the reverse of the {@link #offsetFrom(FieldAbsoluteDate,
  338.      * TimeScale)} method.</p>
  339.      * @param reference reference instant
  340.      * @param apparentOffset apparent clock offset from the reference instant
  341.      * (difference between two readings in the specified time scale)
  342.      * @param timeScale time scale with respect to which the offset is defined
  343.      * @see #offsetFrom(FieldAbsoluteDate, TimeScale)
  344.      */
  345.     public FieldAbsoluteDate(final FieldAbsoluteDate<T> reference, final double apparentOffset, final TimeScale timeScale) {
  346.         this(reference.field, new DateTimeComponents(reference.getComponents(timeScale), apparentOffset),
  347.              timeScale);
  348.     }

  349.     /** Build an instance from mixed double and field raw components.
  350.      * @param epoch reference epoch in seconds from 2000-01-01T12:00:00 TAI
  351.      * @param tA double part of offset since reference epoch
  352.      * @param tB field part of offset since reference epoch
  353.      * @since 9.3
  354.      */
  355.     private FieldAbsoluteDate(final long epoch, final double tA, final T tB) {
  356.         this.field = tB.getField();
  357.         // Use 2Sum for high precision.
  358.         final FieldSumAndResidual<T> sumAndResidual = MathUtils.twoSum(field.getZero().add(tA), tB);
  359.         if (Double.isInfinite(sumAndResidual.getSum().getReal())) {
  360.             this.offset = sumAndResidual.getSum();
  361.             this.epoch  = (sumAndResidual.getSum().getReal() < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
  362.         } else {
  363.             final long dl = (long) FastMath.floor(sumAndResidual.getSum().getReal());
  364.             final T regularOffset = sumAndResidual.getSum().subtract(dl).add(sumAndResidual.getResidual());
  365.             if (regularOffset.getReal() >= 0) {
  366.                 // regular case, the offset is between 0.0 and 1.0
  367.                 this.offset = regularOffset;
  368.                 this.epoch  = epoch + dl;
  369.             } else {
  370.                 // very rare case, the offset is just before a whole second
  371.                 // we will loose some bits of accuracy when adding 1 second
  372.                 // but this will ensure the offset remains in the [0.0; 1.0) interval
  373.                 this.offset = regularOffset.add(1.0);
  374.                 this.epoch  = epoch + dl - 1;
  375.             }
  376.         }
  377.     }

  378.     /** Build an instance from a CCSDS Unsegmented Time Code (CUC).
  379.      * <p>
  380.      * CCSDS Unsegmented Time Code is defined in the blue book:
  381.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  382.      * </p>
  383.      * <p>
  384.      * If the date to be parsed is formatted using version 3 of the standard
  385.      * (CCSDS 301.0-B-3 published in 2002) or if the extension of the preamble
  386.      * field introduced in version 4 of the standard is not used, then the
  387.      * {@code preambleField2} parameter can be set to 0.
  388.      * </p>
  389.      *
  390.      * <p>This method uses the {@link DataContext#getDefault() default data context} if
  391.      * the CCSDS epoch is used.
  392.      *
  393.      * @param field field for the components
  394.      * @param preambleField1 first byte of the field specifying the format, often
  395.      * not transmitted in data interfaces, as it is constant for a given data interface
  396.      * @param preambleField2 second byte of the field specifying the format
  397.      * (added in revision 4 of the CCSDS standard in 2010), often not transmitted in data
  398.      * interfaces, as it is constant for a given data interface (value ignored if presence
  399.      * not signaled in {@code preambleField1})
  400.      * @param timeField byte array containing the time code
  401.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  402.      * specifies the {@link #getCCSDSEpoch(Field) CCSDS reference epoch} is used (and hence
  403.      * may be null in this case)
  404.      * @return an instance corresponding to the specified date
  405.      * @param <T> the type of the field elements
  406.      * @see #parseCCSDSUnsegmentedTimeCode(Field, byte, byte, byte[], FieldAbsoluteDate,
  407.      * FieldAbsoluteDate)
  408.      */
  409.     @DefaultDataContext
  410.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> parseCCSDSUnsegmentedTimeCode(final Field<T> field,
  411.                                                                                                      final byte preambleField1,
  412.                                                                                                      final byte preambleField2,
  413.                                                                                                      final byte[] timeField,
  414.                                                                                                      final FieldAbsoluteDate<T> agencyDefinedEpoch) {
  415.         return parseCCSDSUnsegmentedTimeCode(field, preambleField1, preambleField2,
  416.                 timeField, agencyDefinedEpoch,
  417.                 new FieldAbsoluteDate<>(
  418.                         field,
  419.                         DataContext.getDefault().getTimeScales().getCcsdsEpoch()));
  420.     }

  421.     /**
  422.      * Build an instance from a CCSDS Unsegmented Time Code (CUC).
  423.      * <p>
  424.      * CCSDS Unsegmented Time Code is defined in the blue book: CCSDS Time Code Format
  425.      * (CCSDS 301.0-B-4) published in November 2010
  426.      * </p>
  427.      * <p>
  428.      * If the date to be parsed is formatted using version 3 of the standard (CCSDS
  429.      * 301.0-B-3 published in 2002) or if the extension of the preamble field introduced
  430.      * in version 4 of the standard is not used, then the {@code preambleField2} parameter
  431.      * can be set to 0.
  432.      * </p>
  433.      *
  434.      * @param <T>                the type of the field elements
  435.      * @param field              field for the components
  436.      * @param preambleField1     first byte of the field specifying the format, often not
  437.      *                           transmitted in data interfaces, as it is constant for a
  438.      *                           given data interface
  439.      * @param preambleField2     second byte of the field specifying the format (added in
  440.      *                           revision 4 of the CCSDS standard in 2010), often not
  441.      *                           transmitted in data interfaces, as it is constant for a
  442.      *                           given data interface (value ignored if presence not
  443.      *                           signaled in {@code preambleField1})
  444.      * @param timeField          byte array containing the time code
  445.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field specifies
  446.      *                           the CCSDS reference epoch is used (and hence may be null
  447.      *                           in this case)
  448.      * @param ccsdsEpoch         reference epoch, ignored if the preamble field specifies
  449.      *                           the agency epoch is used.
  450.      * @return an instance corresponding to the specified date
  451.      * @since 10.1
  452.      */
  453.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> parseCCSDSUnsegmentedTimeCode(
  454.             final Field<T> field,
  455.             final byte preambleField1,
  456.             final byte preambleField2,
  457.             final byte[] timeField,
  458.             final FieldAbsoluteDate<T> agencyDefinedEpoch,
  459.             final FieldAbsoluteDate<T> ccsdsEpoch) {

  460.         // time code identification and reference epoch
  461.         final FieldAbsoluteDate<T> epochF;
  462.         switch (preambleField1 & 0x70) {
  463.             case 0x10:
  464.                 // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  465.                 epochF = ccsdsEpoch;
  466.                 break;
  467.             case 0x20:
  468.                 // the reference epoch is agency defined
  469.                 if (agencyDefinedEpoch == null) {
  470.                     throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  471.                 }
  472.                 epochF = agencyDefinedEpoch;
  473.                 break;
  474.             default :
  475.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  476.                                           formatByte(preambleField1));
  477.         }

  478.         // time field lengths
  479.         int coarseTimeLength = 1 + ((preambleField1 & 0x0C) >>> 2);
  480.         int fineTimeLength   = preambleField1 & 0x03;

  481.         if ((preambleField1 & 0x80) != 0x0) {
  482.             // there is an additional octet in preamble field
  483.             coarseTimeLength += (preambleField2 & 0x60) >>> 5;
  484.             fineTimeLength   += (preambleField2 & 0x1C) >>> 2;
  485.         }

  486.         if (timeField.length != coarseTimeLength + fineTimeLength) {
  487.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  488.                                       timeField.length, coarseTimeLength + fineTimeLength);
  489.         }

  490.         T seconds = field.getZero();
  491.         for (int i = 0; i < coarseTimeLength; ++i) {
  492.             seconds = seconds.multiply(256).add(field.getZero().add(toUnsigned(timeField[i])));
  493.         }
  494.         T subseconds = field.getZero();
  495.         for (int i = timeField.length - 1; i >= coarseTimeLength; --i) {
  496.             subseconds = (subseconds.add(toUnsigned(timeField[i]))).divide(256);
  497.         }
  498.         return new FieldAbsoluteDate<>(epochF, seconds).shiftedBy(subseconds);

  499.     }

  500.     /** Build an instance from a CCSDS Day Segmented Time Code (CDS).
  501.      * <p>
  502.      * CCSDS Day Segmented Time Code is defined in the blue book:
  503.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  504.      * </p>
  505.      *
  506.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  507.      *
  508.      * @param field field for the components
  509.      * @param preambleField field specifying the format, often not transmitted in
  510.      * data interfaces, as it is constant for a given data interface
  511.      * @param timeField byte array containing the time code
  512.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  513.      * specifies the {@link #getCCSDSEpoch(Field) CCSDS reference epoch} is used (and hence
  514.      * may be null in this case)
  515.      * @return an instance corresponding to the specified date
  516.      * @param <T> the type of the field elements
  517.      * @see #parseCCSDSDaySegmentedTimeCode(Field, byte, byte[], DateComponents,
  518.      * TimeScale)
  519.      */
  520.     @DefaultDataContext
  521.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> parseCCSDSDaySegmentedTimeCode(final Field<T> field,
  522.                                                                                                       final byte preambleField, final byte[] timeField,
  523.                                                                                                       final DateComponents agencyDefinedEpoch) {
  524.         return parseCCSDSDaySegmentedTimeCode(field, preambleField, timeField,
  525.                 agencyDefinedEpoch, DataContext.getDefault().getTimeScales().getUTC());
  526.     }

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

  553.         // time code identification
  554.         if ((preambleField & 0xF0) != 0x40) {
  555.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  556.                                       formatByte(preambleField));
  557.         }

  558.         // reference epoch
  559.         final DateComponents epochDC;
  560.         if ((preambleField & 0x08) == 0x00) {
  561.             // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  562.             epochDC = DateComponents.CCSDS_EPOCH;
  563.         } else {
  564.             // the reference epoch is agency defined
  565.             if (agencyDefinedEpoch == null) {
  566.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  567.             }
  568.             epochDC = agencyDefinedEpoch;
  569.         }

  570.         // time field lengths
  571.         final int daySegmentLength = ((preambleField & 0x04) == 0x0) ? 2 : 3;
  572.         final int subMillisecondLength = (preambleField & 0x03) << 1;
  573.         if (subMillisecondLength == 6) {
  574.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  575.                                       formatByte(preambleField));
  576.         }
  577.         if (timeField.length != daySegmentLength + 4 + subMillisecondLength) {
  578.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  579.                                       timeField.length, daySegmentLength + 4 + subMillisecondLength);
  580.         }


  581.         int i   = 0;
  582.         int day = 0;
  583.         while (i < daySegmentLength) {
  584.             day = day * 256 + toUnsigned(timeField[i++]);
  585.         }

  586.         long milliInDay = 0l;
  587.         while (i < daySegmentLength + 4) {
  588.             milliInDay = milliInDay * 256 + toUnsigned(timeField[i++]);
  589.         }
  590.         final int milli   = (int) (milliInDay % 1000l);
  591.         final int seconds = (int) ((milliInDay - milli) / 1000l);

  592.         double subMilli = 0;
  593.         double divisor  = 1;
  594.         while (i < timeField.length) {
  595.             subMilli = subMilli * 256 + toUnsigned(timeField[i++]);
  596.             divisor *= 1000;
  597.         }

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

  601.     }

  602.     /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  603.      * <p>
  604.      * CCSDS Calendar Segmented Time Code is defined in the blue book:
  605.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  606.      * </p>
  607.      *
  608.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  609.      *
  610.      * @param preambleField field specifying the format, often not transmitted in
  611.      * data interfaces, as it is constant for a given data interface
  612.      * @param timeField byte array containing the time code
  613.      * @return an instance corresponding to the specified date
  614.      * @see #parseCCSDSCalendarSegmentedTimeCode(byte, byte[], TimeScale)
  615.      */
  616.     @DefaultDataContext
  617.     public FieldAbsoluteDate<T> parseCCSDSCalendarSegmentedTimeCode(final byte preambleField, final byte[] timeField) {
  618.         return parseCCSDSCalendarSegmentedTimeCode(preambleField, timeField,
  619.                 DataContext.getDefault().getTimeScales().getUTC());
  620.     }

  621.     /**
  622.      * Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  623.      * <p>
  624.      * CCSDS Calendar Segmented Time Code is defined in the blue book: CCSDS Time Code
  625.      * Format (CCSDS 301.0-B-4) published in November 2010
  626.      * </p>
  627.      *
  628.      * @param preambleField field specifying the format, often not transmitted in data
  629.      *                      interfaces, as it is constant for a given data interface
  630.      * @param timeField     byte array containing the time code
  631.      * @param utc           time scale used to compute date and time components.
  632.      * @return an instance corresponding to the specified date
  633.      * @since 10.1
  634.      */
  635.     public FieldAbsoluteDate<T> parseCCSDSCalendarSegmentedTimeCode(
  636.             final byte preambleField,
  637.             final byte[] timeField,
  638.             final TimeScale utc) {

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

  644.         // time field length
  645.         final int length = 7 + (preambleField & 0x07);
  646.         if (length == 14) {
  647.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  648.                                       formatByte(preambleField));
  649.         }
  650.         if (timeField.length != length) {
  651.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  652.                                       timeField.length, length);
  653.         }

  654.         // date part in the first four bytes
  655.         final DateComponents date;
  656.         if ((preambleField & 0x08) == 0x00) {
  657.             // month of year and day of month variation
  658.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  659.                                       toUnsigned(timeField[2]),
  660.                                       toUnsigned(timeField[3]));
  661.         } else {
  662.             // day of year variation
  663.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  664.                                       toUnsigned(timeField[2]) * 256 + toUnsigned(timeField[3]));
  665.         }

  666.         // time part from bytes 5 to last (between 7 and 13 depending on precision)
  667.         final TimeComponents time = new TimeComponents(toUnsigned(timeField[4]),
  668.                                                        toUnsigned(timeField[5]),
  669.                                                        toUnsigned(timeField[6]));
  670.         double subSecond = 0;
  671.         double divisor   = 1;
  672.         for (int i = 7; i < length; ++i) {
  673.             subSecond = subSecond * 100 + toUnsigned(timeField[i]);
  674.             divisor *= 100;
  675.         }

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

  677.     }

  678.     /** Decode a signed byte as an unsigned int value.
  679.      * @param b byte to decode
  680.      * @return an unsigned int value
  681.      */
  682.     private static int toUnsigned(final byte b) {
  683.         final int i = (int) b;
  684.         return (i < 0) ? 256 + i : i;
  685.     }

  686.     /** Format a byte as an hex string for error messages.
  687.      * @param data byte to format
  688.      * @return a formatted string
  689.      */
  690.     private static String formatByte(final byte data) {
  691.         return "0x" + Integer.toHexString(data).toUpperCase();
  692.     }

  693.     /** Build an instance corresponding to a Julian Day date.
  694.      * @param jd Julian day
  695.      * @param secondsSinceNoon seconds in the Julian day
  696.      * (BEWARE, Julian days start at noon, so 0.0 is noon)
  697.      * @param timeScale time scale in which the seconds in day are defined
  698.      * @return a new instant
  699.      * @param <T> the type of the field elements
  700.      */
  701.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createJDDate(final int jd, final T secondsSinceNoon,
  702.                                                                                     final TimeScale timeScale) {
  703.         return new FieldAbsoluteDate<>(secondsSinceNoon.getField(), new DateComponents(DateComponents.JULIAN_EPOCH, jd),
  704.                                        TimeComponents.H12, timeScale).shiftedBy(secondsSinceNoon);
  705.     }

  706.     /** Build an instance corresponding to a Modified Julian Day date.
  707.      * @param mjd modified Julian day
  708.      * @param secondsInDay seconds in the day
  709.      * @param timeScale time scale in which the seconds in day are defined
  710.      * @return a new instant
  711.      * @param <T> the type of the field elements
  712.      */
  713.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createMJDDate(final int mjd, final T secondsInDay,
  714.                                                                                      final TimeScale timeScale) {
  715.         return new FieldAbsoluteDate<>(secondsInDay.getField(),
  716.                                        new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, mjd),
  717.                                        TimeComponents.H00,
  718.                                        timeScale).shiftedBy(secondsInDay);
  719.     }

  720.     /** Build an instance corresponding to a GPS date.
  721.      *
  722.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  723.      *
  724.      * <p>GPS dates are provided as a week number starting at
  725.      * {@link #getGPSEpoch(Field) GPS epoch} and as a number of milliseconds
  726.      * since week start.</p>
  727.      * @param weekNumber week number since {@link #getGPSEpoch(Field) GPS epoch}
  728.      * @param milliInWeek number of milliseconds since week start
  729.      * @return a new instant
  730.      * @param <T> the type of the field elements
  731.      * @see #createGPSDate(int, CalculusFieldElement, TimeScale)
  732.      */
  733.     @DefaultDataContext
  734.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createGPSDate(final int weekNumber, final T milliInWeek) {
  735.         return createGPSDate(weekNumber, milliInWeek,
  736.                 DataContext.getDefault().getTimeScales().getGPS());
  737.     }

  738.     /**
  739.      * Build an instance corresponding to a GPS date.
  740.      * <p>GPS dates are provided as a week number starting at
  741.      * {@link #getGPSEpoch(Field) GPS epoch} and as a number of milliseconds since week
  742.      * start.</p>
  743.      *
  744.      * @param <T>         the type of the field elements
  745.      * @param weekNumber  week number since {@link #getGPSEpoch(Field) GPS epoch}
  746.      * @param milliInWeek number of milliseconds since week start
  747.      * @param gps         GPS time scale.
  748.      * @return a new instant
  749.      * @since 10.1
  750.      */
  751.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createGPSDate(
  752.             final int weekNumber,
  753.             final T milliInWeek,
  754.             final TimeScale gps) {

  755.         final int day = (int) FastMath.floor(milliInWeek.getReal() / (1000.0 * Constants.JULIAN_DAY));
  756.         final T secondsInDay = milliInWeek.divide(1000.0).subtract(day * Constants.JULIAN_DAY);
  757.         return new FieldAbsoluteDate<>(milliInWeek.getField(), new DateComponents(DateComponents.GPS_EPOCH, weekNumber * 7 + day),
  758.                                        TimeComponents.H00, gps).shiftedBy(secondsInDay);
  759.     }

  760.     /** Build an instance corresponding to a Julian Epoch (JE).
  761.      * <p>According to Lieske paper: <a
  762.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&amp;defaultprint=YES&amp;filetype=.pdf.">
  763.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
  764.      * vol. 73, no. 3, Mar. 1979, p. 282-284, Julian Epoch is related to Julian Ephemeris Date as:
  765.      * <pre>JE = 2000.0 + (JED - 2451545.0) / 365.25</pre>
  766.      * <p>This method reverts the formula above and computes an {@code FieldAbsoluteDate<T>} from the Julian Epoch.
  767.      *
  768.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  769.      *
  770.      * @param <T> the type of the field elements
  771.      * @param julianEpoch Julian epoch, like 2000.0 for defining the classical reference J2000.0
  772.      * @return a new instant
  773.      * @see #getJ2000Epoch(Field)
  774.      * @see #createBesselianEpoch(CalculusFieldElement)
  775.      * @see #createJulianEpoch(CalculusFieldElement, TimeScales)
  776.      */
  777.     @DefaultDataContext
  778.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createJulianEpoch(final T julianEpoch) {
  779.         return createJulianEpoch(julianEpoch,
  780.                 DataContext.getDefault().getTimeScales());
  781.     }

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

  806.         final Field<T> field = julianEpoch.getField();
  807.         return new FieldAbsoluteDate<>(new FieldAbsoluteDate<>(field, timeScales.getJ2000Epoch()),
  808.                                        julianEpoch.subtract(2000.0).multiply(Constants.JULIAN_YEAR));
  809.     }

  810.     /** Build an instance corresponding to a Besselian Epoch (BE).
  811.      * <p>According to Lieske paper: <a
  812.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&amp;defaultprint=YES&amp;filetype=.pdf.">
  813.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
  814.      * vol. 73, no. 3, Mar. 1979, p. 282-284, Besselian Epoch is related to Julian Ephemeris Date as:</p>
  815.      * <pre>
  816.      * BE = 1900.0 + (JED - 2415020.31352) / 365.242198781
  817.      * </pre>
  818.      * <p>
  819.      * This method reverts the formula above and computes an {@code FieldAbsoluteDate<T>} from the Besselian Epoch.
  820.      * </p>
  821.      *
  822.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  823.      *
  824.      * @param <T> the type of the field elements
  825.      * @param besselianEpoch Besselian epoch, like 1950 for defining the classical reference B1950.0
  826.      * @return a new instant
  827.      * @see #createJulianEpoch(CalculusFieldElement)
  828.      * @see #createBesselianEpoch(CalculusFieldElement, TimeScales)
  829.      */
  830.     @DefaultDataContext
  831.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createBesselianEpoch(final T besselianEpoch) {
  832.         return createBesselianEpoch(besselianEpoch,
  833.                 DataContext.getDefault().getTimeScales());
  834.     }

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

  862.         final Field<T> field = besselianEpoch.getField();
  863.         return new FieldAbsoluteDate<>(new FieldAbsoluteDate<>(field, timeScales.getJ2000Epoch()),
  864.                                        besselianEpoch.subtract(1900).multiply(Constants.BESSELIAN_YEAR).add(
  865.                                        Constants.JULIAN_DAY * (-36525) + Constants.JULIAN_DAY * 0.31352));
  866.     }

  867.     /** Reference epoch for julian dates: -4712-01-01T12:00:00 Terrestrial Time.
  868.      * <p>Both <code>java.util.Date</code> and {@link DateComponents} classes
  869.      * follow the astronomical conventions and consider a year 0 between
  870.      * years -1 and +1, hence this reference date lies in year -4712 and not
  871.      * in year -4713 as can be seen in other documents or programs that obey
  872.      * a different convention (for example the <code>convcal</code> utility).</p>
  873.      *
  874.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  875.      *
  876.      * @param <T> the type of the field elements
  877.      * @param field field for the components
  878.      * @return the reference epoch for julian dates as a FieldAbsoluteDate
  879.      * @see AbsoluteDate#JULIAN_EPOCH
  880.      * @see TimeScales#getJulianEpoch()
  881.      */
  882.     @DefaultDataContext
  883.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getJulianEpoch(final Field<T> field) {
  884.         return new FieldAbsoluteDate<>(field,
  885.                 DataContext.getDefault().getTimeScales().getJulianEpoch());
  886.     }

  887.     /** Reference epoch for modified julian dates: 1858-11-17T00:00:00 Terrestrial Time.
  888.      *
  889.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  890.      *
  891.      * @param <T> the type of the field elements
  892.      * @param field field for the components
  893.      * @return the reference epoch for modified julian dates as a FieldAbsoluteDate
  894.      * @see AbsoluteDate#MODIFIED_JULIAN_EPOCH
  895.      * @see TimeScales#getModifiedJulianEpoch()
  896.      */
  897.     @DefaultDataContext
  898.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getModifiedJulianEpoch(final Field<T> field) {
  899.         return new FieldAbsoluteDate<>(field,
  900.                 DataContext.getDefault().getTimeScales().getModifiedJulianEpoch());
  901.     }

  902.     /** Reference epoch for 1950 dates: 1950-01-01T00:00:00 Terrestrial Time.
  903.      *
  904.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  905.      *
  906.      * @param <T> the type of the field elements
  907.      * @param field field for the components
  908.      * @return the reference epoch for 1950 dates as a FieldAbsoluteDate
  909.      * @see AbsoluteDate#FIFTIES_EPOCH
  910.      * @see TimeScales#getFiftiesEpoch()
  911.      */
  912.     @DefaultDataContext
  913.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getFiftiesEpoch(final Field<T> field) {
  914.         return new FieldAbsoluteDate<>(field,
  915.                 DataContext.getDefault().getTimeScales().getFiftiesEpoch());
  916.     }

  917.     /** Reference epoch for CCSDS Time Code Format (CCSDS 301.0-B-4):
  918.      *
  919.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  920.      *
  921.      * 1958-01-01T00:00:00 International Atomic Time (<em>not</em> UTC).
  922.      * @param <T> the type of the field elements
  923.      * @param field field for the components
  924.      * @return the reference epoch for CCSDS Time Code Format as a FieldAbsoluteDate
  925.      * @see AbsoluteDate#CCSDS_EPOCH
  926.      * @see TimeScales#getCcsdsEpoch()
  927.      */
  928.     @DefaultDataContext
  929.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getCCSDSEpoch(final Field<T> field) {
  930.         return new FieldAbsoluteDate<>(field,
  931.                 DataContext.getDefault().getTimeScales().getCcsdsEpoch());
  932.     }

  933.     /** Reference epoch for Galileo System Time: 1999-08-22T00:00:00 UTC.
  934.      *
  935.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  936.      *
  937.      * @param <T> the type of the field elements
  938.      * @param field field for the components
  939.      * @return the reference epoch for Galileo System Time as a FieldAbsoluteDate
  940.      * @see AbsoluteDate#GALILEO_EPOCH
  941.      * @see TimeScales#getGalileoEpoch()
  942.      */
  943.     @DefaultDataContext
  944.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getGalileoEpoch(final Field<T> field) {
  945.         return new FieldAbsoluteDate<>(field,
  946.                 DataContext.getDefault().getTimeScales().getGalileoEpoch());
  947.     }

  948.     /** Reference epoch for GPS weeks: 1980-01-06T00:00:00 GPS time.
  949.      *
  950.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  951.      *
  952.      * @param <T> the type of the field elements
  953.      * @param field field for the components
  954.      * @return the reference epoch for GPS weeks as a FieldAbsoluteDate
  955.      * @see AbsoluteDate#GPS_EPOCH
  956.      * @see TimeScales#getGpsEpoch()
  957.      */
  958.     @DefaultDataContext
  959.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getGPSEpoch(final Field<T> field) {
  960.         return new FieldAbsoluteDate<>(field,
  961.                 DataContext.getDefault().getTimeScales().getGpsEpoch());
  962.     }

  963.     /** J2000.0 Reference epoch: 2000-01-01T12:00:00 Terrestrial Time (<em>not</em> UTC).
  964.      *
  965.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  966.      *
  967.      * @param <T> the type of the field elements
  968.      * @param field field for the components
  969.      * @return the J2000.0 reference epoch as a FieldAbsoluteDate
  970.      * @see #createJulianEpoch(CalculusFieldElement)
  971.      * @see AbsoluteDate#J2000_EPOCH
  972.      * @see TimeScales#getJ2000Epoch()
  973.      */
  974.     @DefaultDataContext
  975.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getJ2000Epoch(final Field<T> field) {
  976.         return new FieldAbsoluteDate<>(field,
  977.                 DataContext.getDefault().getTimeScales().getJ2000Epoch());
  978.     }

  979.     /** Java Reference epoch: 1970-01-01T00:00:00 Universal Time Coordinate.
  980.      *
  981.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  982.      *
  983.      * <p>
  984.      * Between 1968-02-01 and 1972-01-01, UTC-TAI = 4.213 170 0s + (MJD - 39 126) x 0.002 592s.
  985.      * As on 1970-01-01 MJD = 40587, UTC-TAI = 8.000082s
  986.      * </p>
  987.      * @param <T> the type of the field elements
  988.      * @param field field for the components
  989.      * @return the Java reference epoch as a FieldAbsoluteDate
  990.      * @see AbsoluteDate#JAVA_EPOCH
  991.      * @see TimeScales#getJavaEpoch()
  992.      */
  993.     @DefaultDataContext
  994.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getJavaEpoch(final Field<T> field) {
  995.         return new FieldAbsoluteDate<>(field,
  996.                 DataContext.getDefault().getTimeScales().getJavaEpoch());
  997.     }

  998.     /** Dummy date at infinity in the past direction.
  999.      * @param <T> the type of the field elements
  1000.      * @param field field for the components
  1001.      * @return a dummy date at infinity in the past direction as a FieldAbsoluteDate
  1002.      * @see AbsoluteDate#PAST_INFINITY
  1003.      * @see TimeScales#getPastInfinity()
  1004.      */
  1005.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getPastInfinity(final Field<T> field) {
  1006.         return new FieldAbsoluteDate<>(field, AbsoluteDate.PAST_INFINITY);
  1007.     }

  1008.     /** Dummy date at infinity in the future direction.
  1009.      * @param <T> the type of the field elements
  1010.      * @param field field for the components
  1011.      * @return a dummy date at infinity in the future direction as a FieldAbsoluteDate
  1012.      * @see AbsoluteDate#FUTURE_INFINITY
  1013.      * @see TimeScales#getFutureInfinity()
  1014.      */
  1015.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getFutureInfinity(final Field<T> field) {
  1016.         return new FieldAbsoluteDate<>(field, AbsoluteDate.FUTURE_INFINITY);
  1017.     }

  1018.     /**
  1019.      * Get an arbitrary date. Useful when a non-null date is needed but its values does
  1020.      * not matter.
  1021.      *
  1022.      * @param <T>   the type of the field elements
  1023.      * @param field field for the components
  1024.      * @return an arbitrary date.
  1025.      */
  1026.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> getArbitraryEpoch(
  1027.             final Field<T> field) {

  1028.         return new FieldAbsoluteDate<>(field, AbsoluteDate.ARBITRARY_EPOCH);
  1029.     }


  1030.     /** Get a time-shifted date.
  1031.      * <p>
  1032.      * Calling this method is equivalent to call {@code new FieldAbsoluteDate&lt;&gt;(this, dt)}.
  1033.      * </p>
  1034.      * @param dt time shift in seconds
  1035.      * @return a new date, shifted with respect to instance (which is immutable)
  1036.      * @see org.orekit.utils.PVCoordinates#shiftedBy(double)
  1037.      * @see org.orekit.attitudes.Attitude#shiftedBy(double)
  1038.      * @see org.orekit.orbits.Orbit#shiftedBy(double)
  1039.      * @see org.orekit.propagation.SpacecraftState#shiftedBy(double)
  1040.      */
  1041.     public FieldAbsoluteDate<T> shiftedBy(final T dt) {
  1042.         return new FieldAbsoluteDate<>(this, dt);
  1043.     }

  1044.     /** Compute the physically elapsed duration between two instants.
  1045.      * <p>The returned duration is the number of seconds physically
  1046.      * elapsed between the two instants, measured in a regular time
  1047.      * scale with respect to surface of the Earth (i.e either the {@link
  1048.      * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
  1049.      * GPSScale GPS scale}). It is the only method that gives a
  1050.      * duration with a physical meaning.</p>
  1051.      * <p>This method gives the same result (with less computation)
  1052.      * as calling {@link #offsetFrom(FieldAbsoluteDate, TimeScale)}
  1053.      * with a second argument set to one of the regular scales cited
  1054.      * above.</p>
  1055.      * <p>This method is the reverse of the {@link #FieldAbsoluteDate(FieldAbsoluteDate,
  1056.      * double)} constructor.</p>
  1057.      * @param instant instant to subtract from the instance
  1058.      * @return offset in seconds between the two instants (positive
  1059.      * if the instance is posterior to the argument)
  1060.      * @see #offsetFrom(FieldAbsoluteDate, TimeScale)
  1061.      * @see #FieldAbsoluteDate(FieldAbsoluteDate, double)
  1062.      */
  1063.     public T durationFrom(final FieldAbsoluteDate<T> instant) {
  1064.         return offset.subtract(instant.offset).add(epoch - instant.epoch);
  1065.     }

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

  1088.     /** Compute the apparent clock offset between two instant <em>in the
  1089.      * perspective of a specific {@link TimeScale time scale}</em>.
  1090.      * <p>The offset is the number of seconds counted in the given
  1091.      * time scale between the locations of the two instants, with
  1092.      * all time scale irregularities removed (i.e. considering all
  1093.      * days are exactly 86400 seconds long). This method will give
  1094.      * a result that may not have a physical meaning if the time scale
  1095.      * is irregular. For example since a leap second was introduced at
  1096.      * the end of 2005, the apparent offset between 2005-12-31T23:59:59
  1097.      * and 2006-01-01T00:00:00 is 1 second, but the physical duration
  1098.      * of the corresponding time interval as returned by the {@link
  1099.      * #durationFrom(FieldAbsoluteDate)} method is 2 seconds.</p>
  1100.      * <p>This method is the reverse of the {@link #FieldAbsoluteDate(FieldAbsoluteDate,
  1101.      * double, TimeScale)} constructor.</p>
  1102.      * @param instant instant to subtract from the instance
  1103.      * @param timeScale time scale with respect to which the offset should
  1104.      * be computed
  1105.      * @return apparent clock offset in seconds between the two instants
  1106.      * (positive if the instance is posterior to the argument)
  1107.      * @see #durationFrom(FieldAbsoluteDate)
  1108.      * @see #FieldAbsoluteDate(FieldAbsoluteDate, double, TimeScale)
  1109.      */
  1110.     public T offsetFrom(final FieldAbsoluteDate<T> instant, final TimeScale timeScale) {
  1111.         final long   elapsedDurationA = epoch - instant.epoch;
  1112.         final T elapsedDurationB = offset.add(timeScale.offsetFromTAI(this)).
  1113.                                    subtract(instant.offset.add(timeScale.offsetFromTAI(instant)));
  1114.         return  elapsedDurationB.add(elapsedDurationA);
  1115.     }

  1116.     /** Compute the offset between two time scales at the current instant.
  1117.      * <p>The offset is defined as <i>l₁-l₂</i>
  1118.      * where <i>l₁</i> is the location of the instant in
  1119.      * the <code>scale1</code> time scale and <i>l₂</i> is the
  1120.      * location of the instant in the <code>scale2</code> time scale.</p>
  1121.      * @param scale1 first time scale
  1122.      * @param scale2 second time scale
  1123.      * @return offset in seconds between the two time scales at the
  1124.      * current instant
  1125.      */
  1126.     public T timeScalesOffset(final TimeScale scale1, final TimeScale scale2) {
  1127.         return scale1.offsetFromTAI(this).subtract(scale2.offsetFromTAI(this));
  1128.     }

  1129.     /** Convert the instance to a Java {@link java.util.Date Date}.
  1130.      * <p>Conversion to the Date class induces a loss of precision because
  1131.      * the Date class does not provide sub-millisecond information. Java Dates
  1132.      * are considered to be locations in some times scales.</p>
  1133.      * @param timeScale time scale to use
  1134.      * @return a {@link java.util.Date Date} instance representing the location
  1135.      * of the instant in the time scale
  1136.      */
  1137.     public Date toDate(final TimeScale timeScale) {
  1138.         final double time = epoch + (offset.getReal() + timeScale.offsetFromTAI(this).getReal());
  1139.         return new Date(FastMath.round((time + 10957.5 * 86400.0) * 1000));
  1140.     }

  1141.     /** Split the instance into date/time components.
  1142.      * @param timeScale time scale to use
  1143.      * @return date/time components
  1144.      */
  1145.     public DateTimeComponents getComponents(final TimeScale timeScale) {

  1146.         if (Double.isInfinite(offset.getReal())) {
  1147.             // special handling for past and future infinity
  1148.             if (offset.getReal() < 0) {
  1149.                 return new DateTimeComponents(DateComponents.MIN_EPOCH, TimeComponents.H00);
  1150.             } else {
  1151.                 return new DateTimeComponents(DateComponents.MAX_EPOCH,
  1152.                                               new TimeComponents(23, 59, 59.999));
  1153.             }
  1154.         }

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

  1159.         // split date and time
  1160.         final long   carry = (long) FastMath.floor(sumAndResidual.getSum());
  1161.         double offset2000B = (sumAndResidual.getSum() - carry) + sumAndResidual.getResidual();
  1162.         long   offset2000A = epoch + carry + 43200l;
  1163.         if (offset2000B < 0) {
  1164.             offset2000A -= 1;
  1165.             offset2000B += 1;
  1166.         }
  1167.         long time = offset2000A % 86400l;
  1168.         if (time < 0l) {
  1169.             time += 86400l;
  1170.         }
  1171.         final int date = (int) ((offset2000A - time) / 86400l);

  1172.         // extract calendar elements
  1173.         final DateComponents dateComponents = new DateComponents(DateComponents.J2000_EPOCH, date);
  1174.         // extract time element, accounting for leap seconds
  1175.         final double leap =
  1176.                 timeScale.insideLeap(this) ? timeScale.getLeap(this.toAbsoluteDate()) : 0;
  1177.         final int minuteDuration = timeScale.minuteDuration(this);
  1178.         final TimeComponents timeComponents =
  1179.                 TimeComponents.fromSeconds((int) time, offset2000B, leap, minuteDuration);

  1180.         // build the components
  1181.         return new DateTimeComponents(dateComponents, timeComponents);

  1182.     }

  1183.     /** Split the instance into date/time components for a local time.
  1184.      *
  1185.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1186.      *
  1187.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1188.      * negative Westward UTC)
  1189.      * @return date/time components
  1190.      * @see #getComponents(int, TimeScale)
  1191.      */
  1192.     @DefaultDataContext
  1193.     public DateTimeComponents getComponents(final int minutesFromUTC) {
  1194.         return getComponents(minutesFromUTC,
  1195.                 DataContext.getDefault().getTimeScales().getUTC());
  1196.     }

  1197.     /**
  1198.      * Split the instance into date/time components for a local time.
  1199.      *
  1200.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1201.      *                       negative Westward UTC)
  1202.      * @param utc            time scale used to compute date and time components.
  1203.      * @return date/time components
  1204.      * @since 10.1
  1205.      */
  1206.     public DateTimeComponents getComponents(final int minutesFromUTC,
  1207.                                             final TimeScale utc) {

  1208.         final DateTimeComponents utcComponents = getComponents(utc);

  1209.         // shift the date according to UTC offset, but WITHOUT touching the seconds,
  1210.         // as they may exceed 60.0 during a leap seconds introduction,
  1211.         // and we want to preserve these special cases
  1212.         final double seconds = utcComponents.getTime().getSecond();
  1213.         int minute = utcComponents.getTime().getMinute() + minutesFromUTC;
  1214.         final int hourShift;
  1215.         if (minute < 0) {
  1216.             hourShift = (minute - 59) / 60;
  1217.         } else if (minute > 59) {
  1218.             hourShift = minute / 60;
  1219.         } else {
  1220.             hourShift = 0;
  1221.         }
  1222.         minute -= 60 * hourShift;
  1223.         int hour = utcComponents.getTime().getHour() + hourShift;
  1224.         final int dayShift;
  1225.         if (hour < 0) {
  1226.             dayShift = (hour - 23) / 24;
  1227.         } else if (hour > 23) {
  1228.             dayShift = hour / 24;
  1229.         } else {
  1230.             dayShift = 0;
  1231.         }
  1232.         hour -= 24 * dayShift;

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

  1235.     }

  1236.     /** {@inheritDoc} */
  1237.     public FieldAbsoluteDate<T> getDate() {
  1238.         return this;
  1239.     }

  1240.     /** Get the field.
  1241.      * @return field instance.
  1242.      */
  1243.     public Field<T> getField() {
  1244.         return field;
  1245.     }

  1246.     /** Split the instance into date/time components for a time zone.
  1247.      *
  1248.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1249.      *
  1250.      * @param timeZone time zone
  1251.      * @return date/time components
  1252.      * @see #getComponents(TimeZone, TimeScale)
  1253.      */
  1254.     @DefaultDataContext
  1255.     public DateTimeComponents getComponents(final TimeZone timeZone) {
  1256.         return getComponents(timeZone, DataContext.getDefault().getTimeScales().getUTC());
  1257.     }

  1258.     /** Split the instance into date/time components for a time zone.
  1259.      * @param timeZone time zone
  1260.      * @param utc            time scale used to compute date and time components.
  1261.      * @return date/time components
  1262.      * @since 10.1
  1263.      */
  1264.     public DateTimeComponents getComponents(final TimeZone timeZone,
  1265.                                             final TimeScale utc) {
  1266.         final FieldAbsoluteDate<T> javaEpoch =
  1267.                 new FieldAbsoluteDate<>(field, DateComponents.JAVA_EPOCH, utc);
  1268.         final long milliseconds = FastMath.round((offsetFrom(javaEpoch, utc).getReal()) * 1000);
  1269.         return getComponents(timeZone.getOffset(milliseconds) / 60000, utc);
  1270.     }

  1271.     /** Compare the instance with another date.
  1272.      * @param date other date to compare the instance to
  1273.      * @return a negative integer, zero, or a positive integer as this date
  1274.      * is before, simultaneous, or after the specified date.
  1275.      */
  1276.     public int compareTo(final FieldAbsoluteDate<T> date) {
  1277.         return Double.compare(durationFrom(date).getReal(), 0.0);
  1278.     }


  1279.     /** Check if the instance represents the same time as another instance.
  1280.      * @param date other date
  1281.      * @return true if the instance and the other date refer to the same instant
  1282.      */
  1283.     @SuppressWarnings("unchecked")
  1284.     public boolean equals(final Object date) {

  1285.         if (date == this) {
  1286.             // first fast check
  1287.             return true;
  1288.         }

  1289.         if (date instanceof FieldAbsoluteDate) {
  1290.             return durationFrom((FieldAbsoluteDate<T>) date).getReal() == 0.0;
  1291.         }

  1292.         return false;

  1293.     }

  1294.     /** Check if the instance represents the same time as another.
  1295.      * @param other the instant to compare this date to
  1296.      * @return true if the instance and the argument refer to the same instant
  1297.      * @see #isCloseTo(FieldTimeStamped, double)
  1298.      * @since 10.1
  1299.      */
  1300.     public boolean isEqualTo(final FieldTimeStamped<T> other) {
  1301.         return this.equals(other.getDate());
  1302.     }

  1303.     /** Check if the instance time is close to another.
  1304.      * @param other the instant to compare this date to
  1305.      * @param tolerance the separation, in seconds, under which the two instants will be considered close to each other
  1306.      * @return true if the duration between the instance and the argument is strictly below the tolerance
  1307.      * @see #isEqualTo(FieldTimeStamped)
  1308.      * @since 10.1
  1309.      */
  1310.     public boolean isCloseTo(final FieldTimeStamped<T> other, final double tolerance) {
  1311.         return FastMath.abs(this.durationFrom(other.getDate()).getReal()) < tolerance;
  1312.     }

  1313.     /** Check if the instance represents a time that is strictly before another.
  1314.      * @param other the instant to compare this date to
  1315.      * @return true if the instance is strictly before the argument when ordering chronologically
  1316.      * @see #isBeforeOrEqualTo(FieldTimeStamped)
  1317.      * @since 10.1
  1318.      */
  1319.     public boolean isBefore(final FieldTimeStamped<T> other) {
  1320.         return this.compareTo(other.getDate()) < 0;
  1321.     }

  1322.     /** Check if the instance represents a time that is strictly after another.
  1323.      * @param other the instant to compare this date to
  1324.      * @return true if the instance is strictly after the argument when ordering chronologically
  1325.      * @see #isAfterOrEqualTo(FieldTimeStamped)
  1326.      * @since 10.1
  1327.      */
  1328.     public boolean isAfter(final FieldTimeStamped<T> other) {
  1329.         return this.compareTo(other.getDate()) > 0;
  1330.     }

  1331.     /** Check if the instance represents a time that is before or equal to another.
  1332.      * @param other the instant to compare this date to
  1333.      * @return true if the instance is before (or equal to) the argument when ordering chronologically
  1334.      * @see #isBefore(FieldTimeStamped)
  1335.      * @since 10.1
  1336.      */
  1337.     public boolean isBeforeOrEqualTo(final FieldTimeStamped<T> other) {
  1338.         return this.isEqualTo(other) || this.isBefore(other);
  1339.     }

  1340.     /** Check if the instance represents a time that is after or equal to another.
  1341.      * @param other the instant to compare this date to
  1342.      * @return true if the instance is after (or equal to) the argument when ordering chronologically
  1343.      * @see #isAfterOrEqualTo(FieldTimeStamped)
  1344.      * @since 10.1
  1345.      */
  1346.     public boolean isAfterOrEqualTo(final FieldTimeStamped<T> other) {
  1347.         return this.isEqualTo(other) || this.isAfter(other);
  1348.     }

  1349.     /** Check if the instance represents a time that is strictly between two others representing
  1350.      * the boundaries of a time span. The two boundaries can be provided in any order: in other words,
  1351.      * whether <code>boundary</code> represents a time that is before or after <code>otherBoundary</code> will
  1352.      * not change the result of this method.
  1353.      * @param boundary one end of the time span
  1354.      * @param otherBoundary the other end of the time span
  1355.      * @return true if the instance is strictly between the two arguments when ordering chronologically
  1356.      * @see #isBetweenOrEqualTo(FieldTimeStamped, FieldTimeStamped)
  1357.      * @since 10.1
  1358.      */
  1359.     public boolean isBetween(final FieldTimeStamped<T> boundary, final FieldTimeStamped<T> otherBoundary) {
  1360.         final FieldTimeStamped<T> beginning;
  1361.         final FieldTimeStamped<T> end;
  1362.         if (boundary.getDate().isBefore(otherBoundary)) {
  1363.             beginning = boundary;
  1364.             end = otherBoundary;
  1365.         } else {
  1366.             beginning = otherBoundary;
  1367.             end = boundary;
  1368.         }
  1369.         return this.isAfter(beginning) && this.isBefore(end);
  1370.     }

  1371.     /** Check if the instance represents a time that is between two others representing
  1372.      * the boundaries of a time span, or equal to one of them. The two boundaries can be provided in any order:
  1373.      * in other words, whether <code>boundary</code> represents a time that is before or after
  1374.      * <code>otherBoundary</code> will not change the result of this method.
  1375.      * @param boundary one end of the time span
  1376.      * @param otherBoundary the other end of the time span
  1377.      * @return true if the instance is between the two arguments (or equal to at least one of them)
  1378.      * when ordering chronologically
  1379.      * @see #isBetween(FieldTimeStamped, FieldTimeStamped)
  1380.      * @since 10.1
  1381.      */
  1382.     public boolean isBetweenOrEqualTo(final FieldTimeStamped<T> boundary, final FieldTimeStamped<T> otherBoundary) {
  1383.         return this.isEqualTo(boundary) || this.isEqualTo(otherBoundary) || this.isBetween(boundary, otherBoundary);
  1384.     }

  1385.     /** Get a hashcode for this date.
  1386.      * @return hashcode
  1387.      */
  1388.     public int hashCode() {
  1389.         final long l = Double.doubleToLongBits(durationFrom(AbsoluteDate.ARBITRARY_EPOCH).getReal());
  1390.         return (int) (l ^ (l >>> 32));
  1391.     }

  1392.     /**
  1393.      * Get a String representation of the instant location with up to 16 digits of
  1394.      * precision for the seconds value.
  1395.      *
  1396.      * <p> Since this method is used in exception messages and error handling every
  1397.      * effort is made to return some representation of the instant. If UTC is available
  1398.      * from the default data context then it is used to format the string in UTC. If not
  1399.      * then TAI is used. Finally if the prior attempts fail this method falls back to
  1400.      * converting this class's internal representation to a string.
  1401.      *
  1402.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1403.      *
  1404.      * @return a string representation of the instance, in ISO-8601 format if UTC is
  1405.      * available from the default data context.
  1406.      * @see AbsoluteDate#toString()
  1407.      * @see #toString(TimeScale)
  1408.      * @see DateTimeComponents#toString(int, int)
  1409.      */
  1410.     @DefaultDataContext
  1411.     public String toString() {
  1412.         return toAbsoluteDate().toString();
  1413.     }

  1414.     /**
  1415.      * Get a String representation of the instant location in ISO-8601 format without the
  1416.      * UTC offset and with up to 16 digits of precision for the seconds value.
  1417.      *
  1418.      * @param timeScale time scale to use
  1419.      * @return a string representation of the instance.
  1420.      * @see DateTimeComponents#toString(int, int)
  1421.      */
  1422.     public String toString(final TimeScale timeScale) {
  1423.         return getComponents(timeScale).toStringWithoutUtcOffset();
  1424.     }

  1425.     /** Get a String representation of the instant location for a local time.
  1426.      *
  1427.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1428.      *
  1429.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1430.      * negative Westward UTC).
  1431.      * @return string representation of the instance,
  1432.      * in ISO-8601 format with milliseconds accuracy
  1433.      * @see #toString(int, TimeScale)
  1434.      */
  1435.     @DefaultDataContext
  1436.     public String toString(final int minutesFromUTC) {
  1437.         return toString(minutesFromUTC,
  1438.                 DataContext.getDefault().getTimeScales().getUTC());
  1439.     }

  1440.     /**
  1441.      * Get a String representation of the instant location for a local time.
  1442.      *
  1443.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1444.      *                       negative Westward UTC).
  1445.      * @param utc            time scale used to compute date and time components.
  1446.      * @return string representation of the instance, in ISO-8601 format with milliseconds
  1447.      * accuracy
  1448.      * @since 10.1
  1449.      */
  1450.     public String toString(final int minutesFromUTC, final TimeScale utc) {
  1451.         final int minuteDuration = utc.minuteDuration(this);
  1452.         return getComponents(minutesFromUTC, utc).toString(minuteDuration);
  1453.     }

  1454.     /** Get a String representation of the instant location for a time zone.
  1455.      *
  1456.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1457.      *
  1458.      * @param timeZone time zone
  1459.      * @return string representation of the instance,
  1460.      * in ISO-8601 format with milliseconds accuracy
  1461.      * @see #toString(TimeZone, TimeScale)
  1462.      */
  1463.     @DefaultDataContext
  1464.     public String toString(final TimeZone timeZone) {
  1465.         return toString(timeZone, DataContext.getDefault().getTimeScales().getUTC());
  1466.     }

  1467.     /**
  1468.      * Get a String representation of the instant location for a time zone.
  1469.      *
  1470.      * @param timeZone time zone
  1471.      * @param utc      time scale used to compute date and time components.
  1472.      * @return string representation of the instance, in ISO-8601 format with milliseconds
  1473.      * accuracy
  1474.      * @since 10.1
  1475.      */
  1476.     public String toString(final TimeZone timeZone, final TimeScale utc) {
  1477.         final int minuteDuration = utc.minuteDuration(this);
  1478.         return getComponents(timeZone, utc).toString(minuteDuration);
  1479.     }

  1480.     /** Get a time-shifted date.
  1481.      * <p>
  1482.      * Calling this method is equivalent to call <code>new AbsoluteDate(this, dt)</code>.
  1483.      * </p>
  1484.      * @param dt time shift in seconds
  1485.      * @return a new date, shifted with respect to instance (which is immutable)
  1486.      * @see org.orekit.utils.PVCoordinates#shiftedBy(double)
  1487.      * @see org.orekit.attitudes.Attitude#shiftedBy(double)
  1488.      * @see org.orekit.orbits.Orbit#shiftedBy(double)
  1489.      * @see org.orekit.propagation.SpacecraftState#shiftedBy(double)
  1490.      */

  1491.     @Override
  1492.     public FieldAbsoluteDate<T> shiftedBy(final double dt) {
  1493.         return new FieldAbsoluteDate<>(this, dt);
  1494.     }


  1495.     /** Transform the FieldAbsoluteDate in an AbsoluteDate.
  1496.      * @return AbsoluteDate of the FieldObject
  1497.      * */
  1498.     public AbsoluteDate toAbsoluteDate() {
  1499.         return new AbsoluteDate(epoch, offset.getReal());
  1500.     }

  1501. }