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.time.LocalDateTime;
  20. import java.time.ZoneOffset;
  21. import java.time.format.DateTimeFormatter;
  22. import java.util.Date;
  23. import java.util.TimeZone;

  24. import java.util.concurrent.TimeUnit;
  25. import org.hipparchus.CalculusFieldElement;
  26. import org.hipparchus.Field;
  27. import org.hipparchus.FieldElement;
  28. import org.hipparchus.analysis.differentiation.Derivative;
  29. import org.hipparchus.analysis.differentiation.FieldUnivariateDerivative2;
  30. import org.hipparchus.analysis.differentiation.FieldUnivariateDerivative2Field;
  31. import org.hipparchus.complex.Complex;
  32. import org.hipparchus.util.FastMath;
  33. import org.hipparchus.util.MathUtils;
  34. import org.hipparchus.util.MathUtils.FieldSumAndResidual;
  35. import org.hipparchus.util.MathUtils.SumAndResidual;
  36. import org.orekit.annotation.DefaultDataContext;
  37. import org.orekit.data.DataContext;
  38. import org.orekit.utils.Constants;

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

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

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

  112.     /** Offset from the reference epoch in seconds. */
  113.     private final  T offset;

  114.     /** Field used by default.*/
  115.     private final Field<T> field;

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

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

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

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

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

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

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

  231.     }

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

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

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

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

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

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

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

  329.     /** Build an instance from an {@link Instant instant} in utc time scale.
  330.      * @param field field utilized as default
  331.      * @param instant instant in the utc timescale
  332.      * @since 12.1
  333.      */
  334.     @DefaultDataContext
  335.     public FieldAbsoluteDate(final Field<T> field, final Instant instant) {
  336.         this(field, instant, TimeScalesFactory.getUTC());
  337.     }

  338.     /** Build an instance from an {@link Instant instant} in the {@link UTCScale time scale}.
  339.      * @param field field utilized as default
  340.      * @param instant instant in the time scale
  341.      * @param utcScale utc time scale
  342.      * @since 12.1
  343.      */
  344.     public FieldAbsoluteDate(final Field<T> field, final Instant instant, final UTCScale utcScale) {
  345.         this(field, new DateComponents(DateComponents.JAVA_EPOCH,
  346.                 (int) (instant.getEpochSecond() / 86400l)),
  347.             instantToTimeComponents(instant),
  348.             utcScale);
  349.     }

  350.     /** Build an instance from an elapsed duration since to another instant.
  351.      * <p>It is important to note that the elapsed duration is <em>not</em>
  352.      * the difference between two readings on a time scale.
  353.      * @param since start instant of the measured duration
  354.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  355.      * instant, as measured in a regular time scale
  356.      */
  357.     public FieldAbsoluteDate(final FieldAbsoluteDate<T> since, final double elapsedDuration) {
  358.         this(since.epoch, elapsedDuration, since.offset);
  359.     }

  360.     /** Build an instance from an elapsed duration since to another instant.
  361.      * <p>It is important to note that the elapsed duration is <em>not</em>
  362.      * the difference between two readings on a time scale.
  363.      * @param since start instant of the measured duration
  364.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  365.      * instant, as measured in a regular time scale
  366.      * @param timeUnit {@link TimeUnit} of the elapsed duration
  367.      * @since 12.1
  368.      */
  369.     public FieldAbsoluteDate(final FieldAbsoluteDate<T> since, final long elapsedDuration, final TimeUnit timeUnit) {
  370.         this(since.epoch, elapsedDuration, timeUnit, since.offset);
  371.     }


  372.     /** Build an instance from an elapsed duration since to another instant.
  373.      * <p>It is important to note that the elapsed duration is <em>not</em>
  374.      * the difference between two readings on a time scale.
  375.      * @param since start instant of the measured duration
  376.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  377.      * instant, as measured in a regular time scale
  378.      */
  379.     public FieldAbsoluteDate(final AbsoluteDate since, final T elapsedDuration) {
  380.         this(since.getEpoch(), since.getOffset(), elapsedDuration);
  381.     }

  382.     /** Build an instance from an elapsed duration since to another instant.
  383.      * <p>It is important to note that the elapsed duration is <em>not</em>
  384.      * the difference between two readings on a time scale.
  385.      * @param since start instant of the measured duration
  386.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  387.      * instant, as measured in a regular time scale
  388.      * @param timeUnit {@link TimeUnit} of the elapsed duration
  389.      * @param field field utilized by default
  390.      * @since 12.1
  391.      */
  392.     public FieldAbsoluteDate(final AbsoluteDate since,  final long elapsedDuration, final TimeUnit timeUnit, final Field<T> field) {
  393.         this.field = field;

  394.         final long elapsedDurationNanoseconds = TimeUnit.NANOSECONDS.convert(elapsedDuration, timeUnit);
  395.         final long deltaEpoch = elapsedDurationNanoseconds / TimeUnit.SECONDS.toNanos(1);
  396.         final double deltaOffset = (elapsedDurationNanoseconds - (deltaEpoch * TimeUnit.SECONDS.toNanos(1))) / (double) TimeUnit.SECONDS.toNanos(1);
  397.         final T newOffset = field.getZero().add(since.getOffset()).add(deltaOffset);

  398.         if (newOffset.getReal() >= 1.0) {
  399.             // newOffset is in [1.0, 2.0]
  400.             this.epoch = since.getEpoch() + deltaEpoch + 1L;
  401.             this.offset = newOffset.subtract(1.0);
  402.         } else if (newOffset.getReal() < 0) {
  403.             this.epoch = since.getEpoch() + deltaEpoch - 1L;
  404.             this.offset = newOffset.add(1.0);
  405.         } else {
  406.             this.epoch = since.getEpoch() + deltaEpoch;
  407.             this.offset = newOffset;
  408.         }
  409.     }

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

  431.     /** Build an instance from mixed double and field raw components.
  432.      * @param epoch reference epoch in seconds from 2000-01-01T12:00:00 TAI
  433.      * @param tA double part of offset since reference epoch
  434.      * @param tB field part of offset since reference epoch
  435.      * @since 9.3
  436.      */
  437.     private FieldAbsoluteDate(final long epoch, final double tA, final T tB) {
  438.         this.field = tB.getField();
  439.         // Use 2Sum for high precision.
  440.         final FieldSumAndResidual<T> sumAndResidual = MathUtils.twoSum(field.getZero().add(tA), tB);
  441.         if (Double.isInfinite(sumAndResidual.getSum().getReal())) {
  442.             this.offset = sumAndResidual.getSum();
  443.             this.epoch  = (sumAndResidual.getSum().getReal() < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
  444.         } else {
  445.             final long dl = (long) FastMath.floor(sumAndResidual.getSum().getReal());
  446.             final T regularOffset = sumAndResidual.getSum().subtract(dl).add(sumAndResidual.getResidual());
  447.             if (regularOffset.getReal() >= 0) {
  448.                 // regular case, the offset is between 0.0 and 1.0
  449.                 this.offset = regularOffset;
  450.                 this.epoch  = epoch + dl;
  451.             } else {
  452.                 // very rare case, the offset is just before a whole second
  453.                 // we will lose some bits of accuracy when adding 1 second
  454.                 // but this will ensure the offset remains in the [0.0; 1.0) interval
  455.                 this.offset = regularOffset.add(1.0);
  456.                 this.epoch  = epoch + dl - 1;
  457.             }
  458.         }
  459.     }

  460.     /** Build an instance from mixed double and field raw components.
  461.      * @param epoch reference epoch in seconds from 2000-01-01T12:00:00 TAI
  462.      * @param tA numeric part of offset since reference epoch
  463.      * @param tATimeUnit {@link TimeUnit} for tA
  464.      * @param tB field part of offset since reference epoch
  465.      * @since 12.1
  466.      */
  467.     private FieldAbsoluteDate(final long epoch, final long tA, final TimeUnit tATimeUnit, final T tB) {
  468.         this.field = tB.getField();

  469.         final long elapsedDurationNanoseconds = TimeUnit.NANOSECONDS.convert(tA, tATimeUnit);
  470.         final long deltaEpoch = elapsedDurationNanoseconds / TimeUnit.SECONDS.toNanos(1);
  471.         final double deltaOffset = (elapsedDurationNanoseconds - (deltaEpoch * TimeUnit.SECONDS.toNanos(1))) / (double) TimeUnit.SECONDS.toNanos(1);
  472.         final T newOffset = field.getZero().add(tB).add(deltaOffset);

  473.         if (newOffset.getReal() >= 1.0) {
  474.             // newOffset is in [1.0, 2.0]
  475.             this.epoch = epoch + deltaEpoch + 1L;
  476.             offset = newOffset.subtract(1.0);
  477.         } else if (newOffset.getReal() < 0) {
  478.             this.epoch = epoch + deltaEpoch - 1L;
  479.             offset = newOffset.add(1.0);
  480.         } else {
  481.             this.epoch = epoch + deltaEpoch;
  482.             offset = newOffset;
  483.         }
  484.     }

  485.     /**
  486.      * Creates Field date with offset as univariate derivative of second order, with a unit linear coefficient in time.
  487.      * @return univariate derivative 2 date
  488.      * @since 12.2
  489.      */
  490.     public FieldAbsoluteDate<FieldUnivariateDerivative2<T>> toFUD2Field() {
  491.         final FieldUnivariateDerivative2Field<T> fud2Field = FieldUnivariateDerivative2Field.getUnivariateDerivative2Field(field);
  492.         final AbsoluteDate date = toAbsoluteDate();
  493.         final T fieldShift = durationFrom(date);
  494.         final FieldUnivariateDerivative2<T> fud2Shift = new FieldUnivariateDerivative2<>(fieldShift, field.getOne(),
  495.                 field.getZero());
  496.         return new FieldAbsoluteDate<>(fud2Field, date).shiftedBy(fud2Shift);
  497.     }

  498.     /** Extract time components from an instant within the day.
  499.      * @param instant instant to extract the number of seconds within the day
  500.      * @return time components
  501.      */
  502.     private static TimeComponents instantToTimeComponents(final Instant instant) {
  503.         final int secInDay = (int) (instant.getEpochSecond() % 86400L);
  504.         return new TimeComponents(secInDay, 1.0e-9 * instant.getNano());
  505.     }

  506.     /** Build an instance from a CCSDS Unsegmented Time Code (CUC).
  507.      * <p>
  508.      * CCSDS Unsegmented Time Code is defined in the blue book:
  509.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  510.      * </p>
  511.      * <p>
  512.      * If the date to be parsed is formatted using version 3 of the standard
  513.      * (CCSDS 301.0-B-3 published in 2002) or if the extension of the preamble
  514.      * field introduced in version 4 of the standard is not used, then the
  515.      * {@code preambleField2} parameter can be set to 0.
  516.      * </p>
  517.      *
  518.      * <p>This method uses the {@link DataContext#getDefault() default data context} if
  519.      * the CCSDS epoch is used.
  520.      *
  521.      * @param field field for the components
  522.      * @param preambleField1 first byte of the field specifying the format, often
  523.      * not transmitted in data interfaces, as it is constant for a given data interface
  524.      * @param preambleField2 second byte of the field specifying the format
  525.      * (added in revision 4 of the CCSDS standard in 2010), often not transmitted in data
  526.      * interfaces, as it is constant for a given data interface (value ignored if presence
  527.      * not signaled in {@code preambleField1})
  528.      * @param timeField byte array containing the time code
  529.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  530.      * specifies the {@link #getCCSDSEpoch(Field) CCSDS reference epoch} is used (and hence
  531.      * may be null in this case)
  532.      * @return an instance corresponding to the specified date
  533.      * @param <T> the type of the field elements
  534.      * @see #parseCCSDSUnsegmentedTimeCode(Field, byte, byte, byte[], FieldAbsoluteDate,
  535.      * FieldAbsoluteDate)
  536.      */
  537.     @DefaultDataContext
  538.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> parseCCSDSUnsegmentedTimeCode(final Field<T> field,
  539.                                                                                                          final byte preambleField1,
  540.                                                                                                          final byte preambleField2,
  541.                                                                                                          final byte[] timeField,
  542.                                                                                                          final FieldAbsoluteDate<T> agencyDefinedEpoch) {
  543.         return parseCCSDSUnsegmentedTimeCode(field, preambleField1, preambleField2,
  544.                                              timeField, agencyDefinedEpoch,
  545.                                              new FieldAbsoluteDate<>(
  546.                                                              field,
  547.                                                              DataContext.getDefault().getTimeScales().getCcsdsEpoch()));
  548.     }

  549.     /**
  550.      * Build an instance from a CCSDS Unsegmented Time Code (CUC).
  551.      * <p>
  552.      * CCSDS Unsegmented Time Code is defined in the blue book: CCSDS Time Code Format
  553.      * (CCSDS 301.0-B-4) published in November 2010
  554.      * </p>
  555.      * <p>
  556.      * If the date to be parsed is formatted using version 3 of the standard (CCSDS
  557.      * 301.0-B-3 published in 2002) or if the extension of the preamble field introduced
  558.      * in version 4 of the standard is not used, then the {@code preambleField2} parameter
  559.      * can be set to 0.
  560.      * </p>
  561.      *
  562.      * @param <T>                the type of the field elements
  563.      * @param field              field for the components
  564.      * @param preambleField1     first byte of the field specifying the format, often not
  565.      *                           transmitted in data interfaces, as it is constant for a
  566.      *                           given data interface
  567.      * @param preambleField2     second byte of the field specifying the format (added in
  568.      *                           revision 4 of the CCSDS standard in 2010), often not
  569.      *                           transmitted in data interfaces, as it is constant for a
  570.      *                           given data interface (value ignored if presence not
  571.      *                           signaled in {@code preambleField1})
  572.      * @param timeField          byte array containing the time code
  573.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field specifies
  574.      *                           the CCSDS reference epoch is used (and hence may be null
  575.      *                           in this case)
  576.      * @param ccsdsEpoch         reference epoch, ignored if the preamble field specifies
  577.      *                           the agency epoch is used.
  578.      * @return an instance corresponding to the specified date
  579.      * @since 10.1
  580.      */
  581.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> parseCCSDSUnsegmentedTimeCode(final Field<T> field,
  582.                                                                                                          final byte preambleField1,
  583.                                                                                                          final byte preambleField2,
  584.                                                                                                          final byte[] timeField,
  585.                                                                                                          final FieldAbsoluteDate<T> agencyDefinedEpoch,
  586.                                                                                                          final FieldAbsoluteDate<T> ccsdsEpoch) {
  587.         final CcsdsUnsegmentedTimeCode<FieldAbsoluteDate<T>> timeCode =
  588.             new CcsdsUnsegmentedTimeCode<>(preambleField1, preambleField2, timeField,
  589.                                            agencyDefinedEpoch, ccsdsEpoch);
  590.         return new FieldAbsoluteDate<>(timeCode.getEpoch(), timeCode.getSeconds()).
  591.                shiftedBy(timeCode.getSubSecond());
  592.     }

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

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

  645.         final CcsdsSegmentedTimeCode timeCode = new CcsdsSegmentedTimeCode(preambleField, timeField,
  646.                                                                            agencyDefinedEpoch);
  647.         return new FieldAbsoluteDate<>(field, timeCode.getDate(), timeCode.getTime(), utc).
  648.                shiftedBy(timeCode.getSubSecond());
  649.     }

  650.     /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  651.      * <p>
  652.      * CCSDS Calendar Segmented Time Code is defined in the blue book:
  653.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  654.      * </p>
  655.      *
  656.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  657.      *
  658.      * @param preambleField field specifying the format, often not transmitted in
  659.      * data interfaces, as it is constant for a given data interface
  660.      * @param timeField byte array containing the time code
  661.      * @return an instance corresponding to the specified date
  662.      * @see #parseCCSDSCalendarSegmentedTimeCode(byte, byte[], TimeScale)
  663.      */
  664.     @DefaultDataContext
  665.     public FieldAbsoluteDate<T> parseCCSDSCalendarSegmentedTimeCode(final byte preambleField, final byte[] timeField) {
  666.         return parseCCSDSCalendarSegmentedTimeCode(preambleField, timeField,
  667.                                                    DataContext.getDefault().getTimeScales().getUTC());
  668.     }

  669.     /**
  670.      * Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  671.      * <p>
  672.      * CCSDS Calendar Segmented Time Code is defined in the blue book: CCSDS Time Code
  673.      * Format (CCSDS 301.0-B-4) published in November 2010
  674.      * </p>
  675.      *
  676.      * @param preambleField field specifying the format, often not transmitted in data
  677.      *                      interfaces, as it is constant for a given data interface
  678.      * @param timeField     byte array containing the time code
  679.      * @param utc           time scale used to compute date and time components.
  680.      * @return an instance corresponding to the specified date
  681.      * @since 10.1
  682.      */
  683.     public FieldAbsoluteDate<T> parseCCSDSCalendarSegmentedTimeCode(final byte preambleField,
  684.                                                                     final byte[] timeField,
  685.                                                                     final TimeScale utc) {
  686.         final CcsdsSegmentedTimeCode timeCode = new CcsdsSegmentedTimeCode(preambleField, timeField);
  687.         return new FieldAbsoluteDate<>(field, timeCode.getDate(), timeCode.getTime(), utc).
  688.                shiftedBy(timeCode.getSubSecond());
  689.     }

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

  703.     /** Build an instance corresponding to a Julian Day date.
  704.      * <p>
  705.      * This function should be preferred to {@link #createJDDate(int, CalculusFieldElement, TimeScale)} when the target time scale
  706.      * has a non-constant offset with respect to TAI.
  707.      * <p>
  708.      * The idea is to introduce a pivot time scale that is close to the target time scale but has a constant bias with TAI.
  709.      * <p>
  710.      * For example, to get a date from an MJD in TDB time scale, it's advised to use the TT time scale
  711.      * as a pivot scale. TT is very close to TDB and has constant offset to TAI.
  712.      * </p>
  713.      * @param jd Julian day
  714.      * @param secondsSinceNoon seconds in the Julian day
  715.      * (BEWARE, Julian days start at noon, so 0.0 is noon)
  716.      * @param timeScale time scale in which the seconds in day are defined
  717.      * @param pivotTimeScale pivot timescale used as intermediate timescale
  718.      * @return a new instant
  719.      * @param <T> the type of the field elements
  720.      */
  721.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createJDDate(final int jd, final T secondsSinceNoon,
  722.                                                                                         final TimeScale timeScale,
  723.                                                                                         final TimeScale pivotTimeScale) {
  724.         // Get the date in pivot timescale
  725.         final FieldAbsoluteDate<T> dateInPivotTimeScale = createJDDate(jd, secondsSinceNoon, pivotTimeScale);

  726.         // Compare offsets to TAI of the two time scales
  727.         final T offsetFromTAI = timeScale.offsetFromTAI(dateInPivotTimeScale).
  728.                 subtract(pivotTimeScale.offsetFromTAI(dateInPivotTimeScale));

  729.         // Return date in desired timescale
  730.         return dateInPivotTimeScale.shiftedBy(offsetFromTAI.multiply(-1.));
  731.     }

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

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

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

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

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

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

  832.         final Field<T> field = julianEpoch.getField();
  833.         return new FieldAbsoluteDate<>(new FieldAbsoluteDate<>(field, timeScales.getJ2000Epoch()),
  834.                         julianEpoch.subtract(2000.0).multiply(Constants.JULIAN_YEAR));
  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>, Astronomy and Astrophysics,
  840.      * vol. 73, no. 3, Mar. 1979, p. 282-284, Besselian Epoch is related to Julian Ephemeris Date as:</p>
  841.      * <pre>
  842.      * BE = 1900.0 + (JED - 2415020.31352) / 365.242198781
  843.      * </pre>
  844.      * <p>
  845.      * This method reverts the formula above and computes an {@code FieldAbsoluteDate<T>} from the Besselian Epoch.
  846.      * </p>
  847.      *
  848.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  849.      *
  850.      * @param <T> the type of the field elements
  851.      * @param besselianEpoch Besselian epoch, like 1950 for defining the classical reference B1950.0
  852.      * @return a new instant
  853.      * @see #createJulianEpoch(CalculusFieldElement)
  854.      * @see #createBesselianEpoch(CalculusFieldElement, TimeScales)
  855.      */
  856.     @DefaultDataContext
  857.     public static <T extends CalculusFieldElement<T>> FieldAbsoluteDate<T> createBesselianEpoch(final T besselianEpoch) {
  858.         return createBesselianEpoch(besselianEpoch,
  859.                                     DataContext.getDefault().getTimeScales());
  860.     }

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

  1114.         final long multiplier = timeUnit.convert(1, TimeUnit.SECONDS);
  1115.         final T deltaOffset = offset.getField().getZero().add(offset.subtract(instant.offset).multiply(multiplier).round());

  1116.         return deltaOffset.add(deltaEpoch);
  1117.     }

  1118.     /** Compute the physically elapsed duration between two instants.
  1119.      * <p>The returned duration is the number of seconds physically
  1120.      * elapsed between the two instants, measured in a regular time
  1121.      * scale with respect to surface of the Earth (i.e either the {@link
  1122.      * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
  1123.      * GPSScale GPS scale}). It is the only method that gives a
  1124.      * duration with a physical meaning.</p>
  1125.      * <p>This method gives the same result (with less computation)
  1126.      * as calling {@link #offsetFrom(FieldAbsoluteDate, TimeScale)}
  1127.      * with a second argument set to one of the regular scales cited
  1128.      * above.</p>
  1129.      * <p>This method is the reverse of the {@link #FieldAbsoluteDate(FieldAbsoluteDate,
  1130.      * double)} constructor.</p>
  1131.      * @param instant instant to subtract from the instance
  1132.      * @return offset in seconds between the two instants (positive
  1133.      * if the instance is posterior to the argument)
  1134.      * @see #offsetFrom(FieldAbsoluteDate, TimeScale)
  1135.      * @see #FieldAbsoluteDate(FieldAbsoluteDate, double)
  1136.      */
  1137.     public T durationFrom(final AbsoluteDate instant) {
  1138.         return offset.subtract(instant.getOffset()).add(epoch - instant.getEpoch());
  1139.     }

  1140.     /** Compute the physically elapsed duration between two instants.
  1141.      * <p>The returned duration is the number of seconds physically
  1142.      * elapsed between the two instants, measured in a regular time
  1143.      * scale with respect to surface of the Earth (i.e either the {@link
  1144.      * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
  1145.      * GPSScale GPS scale}). It is the only method that gives a
  1146.      * duration with a physical meaning.</p>
  1147.      * <p>This method gives the same result (with less computation)
  1148.      * as calling {@link #offsetFrom(FieldAbsoluteDate, TimeScale)}
  1149.      * with a second argument set to one of the regular scales cited
  1150.      * above.</p>
  1151.      * <p>This method is the reverse of the {@link #FieldAbsoluteDate(FieldAbsoluteDate,
  1152.      * double)} constructor.</p>
  1153.      * @param instant instant to subtract from the instance
  1154.      * @param timeUnit {@link TimeUnit} precision for the offset
  1155.      * @return offset in the given timeunit between the two instants (positive
  1156.      * if the instance is posterior to the argument), rounded to the nearest integer {@link TimeUnit}
  1157.      * @see #FieldAbsoluteDate(FieldAbsoluteDate, long, TimeUnit)
  1158.      * @since 12.1
  1159.      */
  1160.     public T durationFrom(final AbsoluteDate instant, final TimeUnit timeUnit) {
  1161.         final long deltaEpoch = timeUnit.convert(epoch - instant.getEpoch(), TimeUnit.SECONDS);

  1162.         final long multiplier = timeUnit.convert(1, TimeUnit.SECONDS);
  1163.         final T deltaOffset = offset.getField().getZero().add(offset.subtract(instant.getOffset()).multiply(multiplier).round());

  1164.         return deltaOffset.add(deltaEpoch);
  1165.     }

  1166.     /** Compute the apparent clock offset between two instant <em>in the
  1167.      * perspective of a specific {@link TimeScale time scale}</em>.
  1168.      * <p>The offset is the number of seconds counted in the given
  1169.      * time scale between the locations of the two instants, with
  1170.      * all time scale irregularities removed (i.e. considering all
  1171.      * days are exactly 86400 seconds long). This method will give
  1172.      * a result that may not have a physical meaning if the time scale
  1173.      * is irregular. For example since a leap second was introduced at
  1174.      * the end of 2005, the apparent offset between 2005-12-31T23:59:59
  1175.      * and 2006-01-01T00:00:00 is 1 second, but the physical duration
  1176.      * of the corresponding time interval as returned by the {@link
  1177.      * #durationFrom(FieldAbsoluteDate)} method is 2 seconds.</p>
  1178.      * <p>This method is the reverse of the {@link #FieldAbsoluteDate(FieldAbsoluteDate,
  1179.      * double, TimeScale)} constructor.</p>
  1180.      * @param instant instant to subtract from the instance
  1181.      * @param timeScale time scale with respect to which the offset should
  1182.      * be computed
  1183.      * @return apparent clock offset in seconds between the two instants
  1184.      * (positive if the instance is posterior to the argument)
  1185.      * @see #durationFrom(FieldAbsoluteDate)
  1186.      * @see #FieldAbsoluteDate(FieldAbsoluteDate, double, TimeScale)
  1187.      */
  1188.     public T offsetFrom(final FieldAbsoluteDate<T> instant, final TimeScale timeScale) {
  1189.         final long   elapsedDurationA = epoch - instant.epoch;
  1190.         final T elapsedDurationB = offset.add(timeScale.offsetFromTAI(this)).
  1191.                         subtract(instant.offset.add(timeScale.offsetFromTAI(instant)));
  1192.         return  elapsedDurationB.add(elapsedDurationA);
  1193.     }

  1194.     /** Compute the offset between two time scales at the current instant.
  1195.      * <p>The offset is defined as <i>l₁-l₂</i>
  1196.      * where <i>l₁</i> is the location of the instant in
  1197.      * the <code>scale1</code> time scale and <i>l₂</i> is the
  1198.      * location of the instant in the <code>scale2</code> time scale.</p>
  1199.      * @param scale1 first time scale
  1200.      * @param scale2 second time scale
  1201.      * @return offset in seconds between the two time scales at the
  1202.      * current instant
  1203.      */
  1204.     public T timeScalesOffset(final TimeScale scale1, final TimeScale scale2) {
  1205.         return scale1.offsetFromTAI(this).subtract(scale2.offsetFromTAI(this));
  1206.     }

  1207.     /** Convert the instance to a Java {@link java.util.Date Date}.
  1208.      * <p>Conversion to the Date class induces a loss of precision because
  1209.      * the Date class does not provide sub-millisecond information. Java Dates
  1210.      * are considered to be locations in some times scales.</p>
  1211.      * @param timeScale time scale to use
  1212.      * @return a {@link java.util.Date Date} instance representing the location
  1213.      * of the instant in the time scale
  1214.      */
  1215.     public Date toDate(final TimeScale timeScale) {
  1216.         final double time = epoch + (offset.getReal() + timeScale.offsetFromTAI(this).getReal());
  1217.         return new Date(FastMath.round((time + 10957.5 * 86400.0) * 1000));
  1218.     }

  1219.     /**
  1220.      * Convert the instance to a Java {@link java.time.Instant Instant}.
  1221.      * Nanosecond precision is preserved during this conversion
  1222.      *
  1223.      * @return a {@link java.time.Instant Instant} instance representing the location
  1224.      * of the instant in the utc time scale
  1225.      * @since 12.1
  1226.      */
  1227.     @DefaultDataContext
  1228.     public Instant toInstant() {
  1229.         return toInstant(TimeScalesFactory.getTimeScales());
  1230.     }

  1231.     /**
  1232.      * Convert the instance to a Java {@link java.time.Instant Instant}.
  1233.      * Nanosecond precision is preserved during this conversion
  1234.      *
  1235.      * @param timeScales the timescales to use
  1236.      * @return a {@link java.time.Instant Instant} instance representing the location
  1237.      * of the instant in the utc time scale
  1238.      * @since 12.1
  1239.      */
  1240.     public Instant toInstant(final TimeScales timeScales) {
  1241.         final UTCScale utc = timeScales.getUTC();
  1242.         final String stringWithoutUtcOffset = toStringWithoutUtcOffset(utc, 9);

  1243.         final LocalDateTime localDateTime = LocalDateTime.parse(stringWithoutUtcOffset, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
  1244.         return localDateTime.toInstant(ZoneOffset.UTC);
  1245.     }

  1246.     /** Split the instance into date/time components.
  1247.      * @param timeScale time scale to use
  1248.      * @return date/time components
  1249.      */
  1250.     public DateTimeComponents getComponents(final TimeScale timeScale) {

  1251.         if (Double.isInfinite(offset.getReal())) {
  1252.             // special handling for past and future infinity
  1253.             if (offset.getReal() < 0) {
  1254.                 return new DateTimeComponents(DateComponents.MIN_EPOCH, TimeComponents.H00);
  1255.             } else {
  1256.                 return new DateTimeComponents(DateComponents.MAX_EPOCH,
  1257.                                               new TimeComponents(23, 59, 59.999));
  1258.             }
  1259.         }

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

  1264.         // split date and time
  1265.         final long   carry = (long) FastMath.floor(sumAndResidual.getSum());
  1266.         double offset2000B = (sumAndResidual.getSum() - carry) + sumAndResidual.getResidual();
  1267.         long   offset2000A = epoch + carry + 43200L;
  1268.         if (offset2000B < 0) {
  1269.             offset2000A -= 1;
  1270.             offset2000B += 1;
  1271.         }
  1272.         long time = offset2000A % 86400L;
  1273.         if (time < 0L) {
  1274.             time += 86400L;
  1275.         }
  1276.         final int date = (int) ((offset2000A - time) / 86400L);

  1277.         // extract calendar elements
  1278.         final DateComponents dateComponents = new DateComponents(DateComponents.J2000_EPOCH, date);
  1279.         // extract time element, accounting for leap seconds
  1280.         final double leap = timeScale.insideLeap(this) ? timeScale.getLeap(this.toAbsoluteDate()) : 0;
  1281.         final int minuteDuration = timeScale.minuteDuration(this);
  1282.         final TimeComponents timeComponents = TimeComponents.fromSeconds((int) time, offset2000B, leap, minuteDuration);

  1283.         // build the components
  1284.         return new DateTimeComponents(dateComponents, timeComponents);

  1285.     }

  1286.     /** Split the instance into date/time components for a local time.
  1287.      *
  1288.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1289.      *
  1290.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1291.      * negative Westward UTC)
  1292.      * @return date/time components
  1293.      * @see #getComponents(int, TimeScale)
  1294.      */
  1295.     @DefaultDataContext
  1296.     public DateTimeComponents getComponents(final int minutesFromUTC) {
  1297.         return getComponents(minutesFromUTC,
  1298.                              DataContext.getDefault().getTimeScales().getUTC());
  1299.     }

  1300.     /**
  1301.      * Split the instance into date/time components for a local time.
  1302.      *
  1303.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1304.      *                       negative Westward UTC)
  1305.      * @param utc            time scale used to compute date and time components.
  1306.      * @return date/time components
  1307.      * @since 10.1
  1308.      */
  1309.     public DateTimeComponents getComponents(final int minutesFromUTC,
  1310.                                             final TimeScale utc) {

  1311.         final DateTimeComponents utcComponents = getComponents(utc);

  1312.         // shift the date according to UTC offset, but WITHOUT touching the seconds,
  1313.         // as they may exceed 60.0 during a leap seconds introduction,
  1314.         // and we want to preserve these special cases
  1315.         final double seconds = utcComponents.getTime().getSecond();
  1316.         int minute = utcComponents.getTime().getMinute() + minutesFromUTC;
  1317.         final int hourShift;
  1318.         if (minute < 0) {
  1319.             hourShift = (minute - 59) / 60;
  1320.         } else if (minute > 59) {
  1321.             hourShift = minute / 60;
  1322.         } else {
  1323.             hourShift = 0;
  1324.         }
  1325.         minute -= 60 * hourShift;
  1326.         int hour = utcComponents.getTime().getHour() + hourShift;
  1327.         final int dayShift;
  1328.         if (hour < 0) {
  1329.             dayShift = (hour - 23) / 24;
  1330.         } else if (hour > 23) {
  1331.             dayShift = hour / 24;
  1332.         } else {
  1333.             dayShift = 0;
  1334.         }
  1335.         hour -= 24 * dayShift;

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

  1338.     }

  1339.     /** {@inheritDoc} */
  1340.     @Override
  1341.     public FieldAbsoluteDate<T> getDate() {
  1342.         return this;
  1343.     }

  1344.     /** Get the field.
  1345.      * @return field instance.
  1346.      */
  1347.     public Field<T> getField() {
  1348.         return field;
  1349.     }

  1350.     /** Split the instance into date/time components for a time zone.
  1351.      *
  1352.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1353.      *
  1354.      * @param timeZone time zone
  1355.      * @return date/time components
  1356.      * @see #getComponents(TimeZone, TimeScale)
  1357.      */
  1358.     @DefaultDataContext
  1359.     public DateTimeComponents getComponents(final TimeZone timeZone) {
  1360.         return getComponents(timeZone, DataContext.getDefault().getTimeScales().getUTC());
  1361.     }

  1362.     /** Split the instance into date/time components for a time zone.
  1363.      * @param timeZone time zone
  1364.      * @param utc            time scale used to compute date and time components.
  1365.      * @return date/time components
  1366.      * @since 10.1
  1367.      */
  1368.     public DateTimeComponents getComponents(final TimeZone timeZone,
  1369.                                             final TimeScale utc) {
  1370.         final FieldAbsoluteDate<T> javaEpoch =
  1371.                         new FieldAbsoluteDate<>(field, DateComponents.JAVA_EPOCH, utc);
  1372.         final long milliseconds = FastMath.round((offsetFrom(javaEpoch, utc).getReal()) * 1000);
  1373.         return getComponents(timeZone.getOffset(milliseconds) / 60000, utc);
  1374.     }

  1375.     /** Compare the instance with another date.
  1376.      * @param date other date to compare the instance to
  1377.      * @return a negative integer, zero, or a positive integer as this date
  1378.      * is before, simultaneous, or after the specified date.
  1379.      */
  1380.     public int compareTo(final FieldAbsoluteDate<T> date) {
  1381.         return Double.compare(durationFrom(date).getReal(), 0.0);
  1382.     }


  1383.     /** Check if the instance represents the same time as another instance.
  1384.      * @param date other date
  1385.      * @return true if the instance and the other date refer to the same instant
  1386.      */
  1387.     @SuppressWarnings("unchecked")
  1388.     public boolean equals(final Object date) {

  1389.         if (date == this) {
  1390.             // first fast check
  1391.             return true;
  1392.         }

  1393.         if (date instanceof FieldAbsoluteDate) {
  1394.             return durationFrom((FieldAbsoluteDate<T>) date).getReal() == 0.0;
  1395.         }

  1396.         return false;

  1397.     }

  1398.     /** Check if the instance represents the same time as another.
  1399.      * @param other the instant to compare this date to
  1400.      * @return true if the instance and the argument refer to the same instant
  1401.      * @see #isCloseTo(FieldTimeStamped, double)
  1402.      * @since 10.1
  1403.      */
  1404.     public boolean isEqualTo(final FieldTimeStamped<T> other) {
  1405.         return this.equals(other.getDate());
  1406.     }

  1407.     /** Check if the instance time is close to another.
  1408.      * @param other the instant to compare this date to
  1409.      * @param tolerance the separation, in seconds, under which the two instants will be considered close to each other
  1410.      * @return true if the duration between the instance and the argument is strictly below the tolerance
  1411.      * @see #isEqualTo(FieldTimeStamped)
  1412.      * @since 10.1
  1413.      */
  1414.     public boolean isCloseTo(final FieldTimeStamped<T> other, final double tolerance) {
  1415.         return FastMath.abs(this.durationFrom(other.getDate()).getReal()) < tolerance;
  1416.     }

  1417.     /** Check if the instance represents a time that is strictly before another.
  1418.      * @param other the instant to compare this date to
  1419.      * @return true if the instance is strictly before the argument when ordering chronologically
  1420.      * @see #isBeforeOrEqualTo(FieldTimeStamped)
  1421.      * @since 10.1
  1422.      */
  1423.     public boolean isBefore(final FieldTimeStamped<T> other) {
  1424.         return this.compareTo(other.getDate()) < 0;
  1425.     }

  1426.     /** Check if the instance represents a time that is strictly after another.
  1427.      * @param other the instant to compare this date to
  1428.      * @return true if the instance is strictly after the argument when ordering chronologically
  1429.      * @see #isAfterOrEqualTo(FieldTimeStamped)
  1430.      * @since 10.1
  1431.      */
  1432.     public boolean isAfter(final FieldTimeStamped<T> other) {
  1433.         return this.compareTo(other.getDate()) > 0;
  1434.     }

  1435.     /** Check if the instance represents a time that is before or equal to another.
  1436.      * @param other the instant to compare this date to
  1437.      * @return true if the instance is before (or equal to) the argument when ordering chronologically
  1438.      * @see #isBefore(FieldTimeStamped)
  1439.      * @since 10.1
  1440.      */
  1441.     public boolean isBeforeOrEqualTo(final FieldTimeStamped<T> other) {
  1442.         return this.isEqualTo(other) || this.isBefore(other);
  1443.     }

  1444.     /** Check if the instance represents a time that is after or equal to another.
  1445.      * @param other the instant to compare this date to
  1446.      * @return true if the instance is after (or equal to) the argument when ordering chronologically
  1447.      * @see #isAfterOrEqualTo(FieldTimeStamped)
  1448.      * @since 10.1
  1449.      */
  1450.     public boolean isAfterOrEqualTo(final FieldTimeStamped<T> other) {
  1451.         return this.isEqualTo(other) || this.isAfter(other);
  1452.     }

  1453.     /** Check if the instance represents a time that is strictly between two others representing
  1454.      * the boundaries of a time span. The two boundaries can be provided in any order: in other words,
  1455.      * whether <code>boundary</code> represents a time that is before or after <code>otherBoundary</code> will
  1456.      * not change the result of this method.
  1457.      * @param boundary one end of the time span
  1458.      * @param otherBoundary the other end of the time span
  1459.      * @return true if the instance is strictly between the two arguments when ordering chronologically
  1460.      * @see #isBetweenOrEqualTo(FieldTimeStamped, FieldTimeStamped)
  1461.      * @since 10.1
  1462.      */
  1463.     public boolean isBetween(final FieldTimeStamped<T> boundary, final FieldTimeStamped<T> otherBoundary) {
  1464.         final FieldTimeStamped<T> beginning;
  1465.         final FieldTimeStamped<T> end;
  1466.         if (boundary.getDate().isBefore(otherBoundary)) {
  1467.             beginning = boundary;
  1468.             end = otherBoundary;
  1469.         } else {
  1470.             beginning = otherBoundary;
  1471.             end = boundary;
  1472.         }
  1473.         return this.isAfter(beginning) && this.isBefore(end);
  1474.     }

  1475.     /** Check if the instance represents a time that is between two others representing
  1476.      * the boundaries of a time span, or equal to one of them. The two boundaries can be provided in any order:
  1477.      * in other words, whether <code>boundary</code> represents a time that is before or after
  1478.      * <code>otherBoundary</code> will not change the result of this method.
  1479.      * @param boundary one end of the time span
  1480.      * @param otherBoundary the other end of the time span
  1481.      * @return true if the instance is between the two arguments (or equal to at least one of them)
  1482.      * when ordering chronologically
  1483.      * @see #isBetween(FieldTimeStamped, FieldTimeStamped)
  1484.      * @since 10.1
  1485.      */
  1486.     public boolean isBetweenOrEqualTo(final FieldTimeStamped<T> boundary, final FieldTimeStamped<T> otherBoundary) {
  1487.         return this.isEqualTo(boundary) || this.isEqualTo(otherBoundary) || this.isBetween(boundary, otherBoundary);
  1488.     }

  1489.     /** Get a hashcode for this date.
  1490.      * @return hashcode
  1491.      */
  1492.     public int hashCode() {
  1493.         final long l = Double.doubleToLongBits(durationFrom(AbsoluteDate.ARBITRARY_EPOCH).getReal());
  1494.         return (int) (l ^ (l >>> 32));
  1495.     }

  1496.     /**
  1497.      * Get a String representation of the instant location with up to 16 digits of
  1498.      * precision for the seconds value.
  1499.      *
  1500.      * <p> Since this method is used in exception messages and error handling every
  1501.      * effort is made to return some representation of the instant. If UTC is available
  1502.      * from the default data context then it is used to format the string in UTC. If not
  1503.      * then TAI is used. Finally if the prior attempts fail this method falls back to
  1504.      * converting this class's internal representation to a string.
  1505.      *
  1506.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1507.      *
  1508.      * @return a string representation of the instance, in ISO-8601 format if UTC is
  1509.      * available from the default data context.
  1510.      * @see AbsoluteDate#toString()
  1511.      * @see #toString(TimeScale)
  1512.      * @see DateTimeComponents#toString(int, int)
  1513.      */
  1514.     @DefaultDataContext
  1515.     public String toString() {
  1516.         return toAbsoluteDate().toString();
  1517.     }

  1518.     /**
  1519.      * Get a String representation of the instant location in ISO-8601 format without the
  1520.      * UTC offset and with up to 16 digits of precision for the seconds value.
  1521.      *
  1522.      * @param timeScale time scale to use
  1523.      * @return a string representation of the instance.
  1524.      * @see DateTimeComponents#toString(int, int)
  1525.      */
  1526.     public String toString(final TimeScale timeScale) {
  1527.         return getComponents(timeScale).toStringWithoutUtcOffset();
  1528.     }

  1529.     /** Get a String representation of the instant location for a local time.
  1530.      *
  1531.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1532.      *
  1533.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1534.      * negative Westward UTC).
  1535.      * @return string representation of the instance,
  1536.      * in ISO-8601 format with milliseconds accuracy
  1537.      * @see #toString(int, TimeScale)
  1538.      */
  1539.     @DefaultDataContext
  1540.     public String toString(final int minutesFromUTC) {
  1541.         return toString(minutesFromUTC,
  1542.                         DataContext.getDefault().getTimeScales().getUTC());
  1543.     }

  1544.     /**
  1545.      * Get a String representation of the instant location for a local time.
  1546.      *
  1547.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1548.      *                       negative Westward UTC).
  1549.      * @param utc            time scale used to compute date and time components.
  1550.      * @return string representation of the instance, in ISO-8601 format with milliseconds
  1551.      * accuracy
  1552.      * @since 10.1
  1553.      */
  1554.     public String toString(final int minutesFromUTC, final TimeScale utc) {
  1555.         final int minuteDuration = utc.minuteDuration(this);
  1556.         return getComponents(minutesFromUTC, utc).toString(minuteDuration);
  1557.     }

  1558.     /** Get a String representation of the instant location for a time zone.
  1559.      *
  1560.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1561.      *
  1562.      * @param timeZone time zone
  1563.      * @return string representation of the instance,
  1564.      * in ISO-8601 format with milliseconds accuracy
  1565.      * @see #toString(TimeZone, TimeScale)
  1566.      */
  1567.     @DefaultDataContext
  1568.     public String toString(final TimeZone timeZone) {
  1569.         return toString(timeZone, DataContext.getDefault().getTimeScales().getUTC());
  1570.     }

  1571.     /**
  1572.      * Get a String representation of the instant location for a time zone.
  1573.      *
  1574.      * @param timeZone time zone
  1575.      * @param utc      time scale used to compute date and time components.
  1576.      * @return string representation of the instance, in ISO-8601 format with milliseconds
  1577.      * accuracy
  1578.      * @since 10.1
  1579.      */
  1580.     public String toString(final TimeZone timeZone, final TimeScale utc) {
  1581.         final int minuteDuration = utc.minuteDuration(this);
  1582.         return getComponents(timeZone, utc).toString(minuteDuration);
  1583.     }

  1584.     /**
  1585.      * Return a string representation of this date-time, rounded to the given precision.
  1586.      *
  1587.      * <p>The format used is ISO8601 without the UTC offset.</p>
  1588.      *
  1589.      *
  1590.      * @param timeScale      to use to compute components.
  1591.      * @param fractionDigits the number of digits to include after the decimal point in
  1592.      *                       the string representation of the seconds. The date and time
  1593.      *                       is first rounded as necessary. {@code fractionDigits} must be
  1594.      *                       greater than or equal to {@code 0}.
  1595.      * @return string representation of this date, time, and UTC offset
  1596.      * @see #toString(TimeScale)
  1597.      * @see DateTimeComponents#toString(int, int)
  1598.      * @see DateTimeComponents#toStringWithoutUtcOffset(int, int)
  1599.      * @since 12.2
  1600.      */
  1601.     public String toStringWithoutUtcOffset(final TimeScale timeScale,
  1602.         final int fractionDigits) {
  1603.         return this.getComponents(timeScale)
  1604.             .toStringWithoutUtcOffset(timeScale.minuteDuration(this), fractionDigits);
  1605.     }

  1606.     /** Get a time-shifted date.
  1607.      * <p>
  1608.      * Calling this method is equivalent to call <code>new FieldAbsoluteDate(this, dt)</code>.
  1609.      * </p>
  1610.      * @param dt time shift in seconds
  1611.      * @return a new date, shifted with respect to instance (which is immutable)
  1612.      * @see org.orekit.utils.FieldPVCoordinates#shiftedBy(double)
  1613.      * @see org.orekit.attitudes.FieldAttitude#shiftedBy(double)
  1614.      * @see org.orekit.orbits.FieldOrbit#shiftedBy(double)
  1615.      * @see org.orekit.propagation.FieldSpacecraftState#shiftedBy(double)
  1616.      */
  1617.     @Override
  1618.     public FieldAbsoluteDate<T> shiftedBy(final double dt) {
  1619.         return new FieldAbsoluteDate<>(this, dt);
  1620.     }

  1621.     /** Get a time-shifted date.
  1622.      * <p>
  1623.      * Calling this method is equivalent to call <code>new FieldAbsoluteDate(this, dt, timeUnit)</code>.
  1624.      * </p>
  1625.      * @param dt time shift in time units
  1626.      * @param timeUnit {@link TimeUnit} for dt
  1627.      * @return a new date, shifted with respect to instance (which is immutable)
  1628.      * @see org.orekit.utils.FieldPVCoordinates#shiftedBy(double)
  1629.      * @see org.orekit.attitudes.FieldAttitude#shiftedBy(double)
  1630.      * @see org.orekit.orbits.FieldOrbit#shiftedBy(double)
  1631.      * @see org.orekit.propagation.FieldSpacecraftState#shiftedBy(double)
  1632.      * @since 12.1
  1633.      */
  1634.     public FieldAbsoluteDate<T> shiftedBy(final long dt, final TimeUnit timeUnit) {
  1635.         return new FieldAbsoluteDate<>(this, dt, timeUnit);
  1636.     }


  1637.     /** Transform the FieldAbsoluteDate in an AbsoluteDate.
  1638.      * @return AbsoluteDate of the FieldObject
  1639.      * */
  1640.     public AbsoluteDate toAbsoluteDate() {
  1641.         return new AbsoluteDate(epoch, offset.getReal());
  1642.     }

  1643.     /** Check if the Field is semantically equal to zero.
  1644.      *
  1645.      * <p> Using {@link FieldElement#isZero()}
  1646.      *
  1647.      * @return true the Field is semantically equal to zero
  1648.      * @since 12.0
  1649.      */
  1650.     public boolean hasZeroField() {
  1651.         return (offset instanceof Derivative<?> || offset instanceof Complex) && offset.subtract(offset.getReal()).isZero();
  1652.     }

  1653.     /**
  1654.      * Return the given date as a Modified Julian Date <b>expressed in UTC</b>.
  1655.      *
  1656.      * @return double representation of the given date as Modified Julian Date.
  1657.      * @since 12.2
  1658.      */
  1659.     @DefaultDataContext
  1660.     public T getMJD() {
  1661.         return this.getMJD(TimeScalesFactory.getUTC());
  1662.     }

  1663.     /**
  1664.      * Return the given date as a Modified Julian Date expressed in given timescale.
  1665.      *
  1666.      * @param ts time scale
  1667.      * @return double representation of the given date as Modified Julian Date.
  1668.      * @since 12.2
  1669.      */
  1670.     public T getMJD(final TimeScale ts) {
  1671.         final AbsoluteDate absoluteDate = toAbsoluteDate();
  1672.         final T shift = durationFrom(absoluteDate).divide(Constants.JULIAN_DAY);
  1673.         return shift.add(absoluteDate.getMJD(ts));
  1674.     }

  1675.     /**
  1676.      * Return the given date as a Julian Date <b>expressed in UTC</b>.
  1677.      *
  1678.      * @return double representation of the given date as Julian Date.
  1679.      * @since 12.2
  1680.      */
  1681.     @DefaultDataContext
  1682.     public T getJD() {
  1683.         return getJD(TimeScalesFactory.getUTC());
  1684.     }

  1685.     /**
  1686.      * Return the given date as a Julian Date expressed in given timescale.
  1687.      *
  1688.      * @param ts time scale
  1689.      * @return double representation of the given date as Julian Date.
  1690.      * @since 12.2
  1691.      */
  1692.     public T getJD(final TimeScale ts) {
  1693.         final AbsoluteDate absoluteDate = toAbsoluteDate();
  1694.         final T shift = durationFrom(absoluteDate).divide(Constants.JULIAN_DAY);
  1695.         return shift.add(absoluteDate.getJD(ts));
  1696.     }
  1697. }