FieldAbsoluteDate.java

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

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

  20. import org.hipparchus.Field;
  21. import org.hipparchus.RealFieldElement;
  22. import org.hipparchus.util.FastMath;
  23. import org.orekit.annotation.DefaultDataContext;
  24. import org.orekit.data.DataContext;
  25. import org.orekit.errors.OrekitException;
  26. import org.orekit.errors.OrekitMessages;
  27. import org.orekit.utils.Constants;

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

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

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

  100.     /** Offset from the reference epoch in seconds. */
  101.     private final  T offset;

  102.     /** Field used by default.*/
  103.     private Field<T> field;

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

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

  127.     /** Build an instance from an elapsed duration since to another instant.
  128.      * <p>It is important to note that the elapsed duration is <em>not</em>
  129.      * the difference between two readings on a time scale. As an example,
  130.      * the duration between the two instants leading to the readings
  131.      * 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the {@link UTCScale UTC}
  132.      * time scale is <em>not</em> 1 second, but a stop watch would have measured
  133.      * an elapsed duration of 2 seconds between these two instances because a leap
  134.      * second was introduced at the end of 2005 in this time scale.</p>
  135.      * <p>This constructor is the reverse of the {@link #durationFrom(FieldAbsoluteDate)}
  136.      * method.</p>
  137.      * @param since start instant of the measured duration
  138.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  139.      * instant, as measured in a regular time scale
  140.      * @see #durationFrom(FieldAbsoluteDate)
  141.      */
  142.     public FieldAbsoluteDate(final FieldAbsoluteDate<T> since, final T elapsedDuration) {
  143.         this.field = since.field;
  144.         final T sum = since.offset.add(elapsedDuration);
  145.         if (Double.isInfinite(sum.getReal())) {
  146.             offset = sum;
  147.             epoch  = (sum.getReal() < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
  148.         } else {
  149.             // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
  150.             // the following statements must NOT be simplified, they rely on floating point
  151.             // arithmetic properties (rounding and representable numbers)
  152.             // at the end, the EXACT result of addition since.offset + elapsedDuration
  153.             // is sum + residual, where sum is the closest representable number to the exact
  154.             // result and residual is the missing part that does not fit in the first number
  155.             final double oPrime   = sum.getReal() - elapsedDuration.getReal();
  156.             final double dPrime   = sum.getReal() - oPrime;
  157.             final double deltaO   = since.offset.getReal() - oPrime;
  158.             final double deltaD   = elapsedDuration.getReal() - dPrime;
  159.             final double residual = deltaO + deltaD;
  160.             final long   dl       = (long) FastMath.floor(sum.getReal());
  161.             offset = sum.subtract(dl).add(residual);
  162.             epoch  = since.epoch + dl;
  163.         }
  164.     }

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

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

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

  201.         // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
  202.         // the following statements must NOT be simplified, they rely on floating point
  203.         // arithmetic properties (rounding and representable numbers)
  204.         // at the end, the EXACT result of addition seconds + tsOffset
  205.         // is sum + residual, where sum is the closest representable number to the exact
  206.         // result and residual is the missing part that does not fit in the first number
  207.         final double sum      = seconds + tsOffset;
  208.         final double sPrime   = sum - tsOffset;
  209.         final double tPrime   = sum - sPrime;
  210.         final double deltaS   = seconds  - sPrime;
  211.         final double deltaT   = tsOffset - tPrime;
  212.         final double residual = deltaS   + deltaT;
  213.         final long   dl       = (long) FastMath.floor(sum);

  214.         offset = field.getZero().add((sum - dl) + residual);

  215.         epoch  = 60l * ((date.getJ2000Day() * 24l + time.getHour()) * 60l +
  216.                         time.getMinute() - time.getMinutesFromUTC() - 720l) + dl;
  217.         this.field = field;

  218.     }

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

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

  253.     /** Build an instance from a location in a {@link TimeScale time scale}.
  254.      * <p>The hour is set to 00:00:00.000.</p>
  255.      * @param field field utilized by default
  256.      * @param date date location in the time scale
  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 DateComponents date, final TimeScale timeScale)
  262.         throws IllegalArgumentException {
  263.         this(field, date, TimeComponents.H00, timeScale);
  264.     }

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

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

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


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


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

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

  345.     /** Build an instance from mixed double and field raw components.
  346.      * @param epoch reference epoch in seconds from 2000-01-01T12:00:00 TAI
  347.      * @param tA double part of offset since reference epoch
  348.      * @param tB field part of offset since reference epoch
  349.      * @since 9.3
  350.      */
  351.     private FieldAbsoluteDate(final long epoch, final double tA, final T tB) {
  352.         this.field = tB.getField();
  353.         final T sum = tB.add(tA);
  354.         if (Double.isInfinite(sum.getReal())) {
  355.             this.offset = sum;
  356.             this.epoch  = (sum.getReal() < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
  357.         } else {
  358.             // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
  359.             // the following statements must NOT be simplified, they rely on floating point
  360.             // arithmetic properties (rounding and representable numbers)
  361.             // at the end, the EXACT result of addition tA + tB
  362.             // is sum + residual, where sum is the closest representable number to the exact
  363.             // result and residual is the missing part that does not fit in the first number
  364.             final double oPrime   = sum.getReal() - tA;
  365.             final double dPrime   = sum.getReal() - oPrime;
  366.             final double deltaO   = tB.getReal() - oPrime;
  367.             final double deltaD   = tA - dPrime;
  368.             final double residual = deltaO + deltaD;
  369.             final long   dl       = (long) FastMath.floor(sum.getReal());
  370.             this.offset = sum.subtract(dl).add(residual);
  371.             this.epoch  = epoch + dl;
  372.         }
  373.     }

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

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

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

  474.         // time field lengths
  475.         int coarseTimeLength = 1 + ((preambleField1 & 0x0C) >>> 2);
  476.         int fineTimeLength   = preambleField1 & 0x03;

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

  482.         if (timeField.length != coarseTimeLength + fineTimeLength) {
  483.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  484.                                       timeField.length, coarseTimeLength + fineTimeLength);
  485.         }

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

  495.     }

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

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

  549.         // time code identification
  550.         if ((preambleField & 0xF0) != 0x40) {
  551.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  552.                                       formatByte(preambleField));
  553.         }

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

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


  577.         int i   = 0;
  578.         int day = 0;
  579.         while (i < daySegmentLength) {
  580.             day = day * 256 + toUnsigned(timeField[i++]);
  581.         }

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

  588.         double subMilli = 0;
  589.         double divisor  = 1;
  590.         while (i < timeField.length) {
  591.             subMilli = subMilli * 256 + toUnsigned(timeField[i++]);
  592.             divisor *= 1000;
  593.         }

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

  597.     }

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

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

  635.         // time code identification
  636.         if ((preambleField & 0xF0) != 0x50) {
  637.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  638.                                       formatByte(preambleField));
  639.         }

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

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

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

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

  673.     }

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

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

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

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

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

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

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

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

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

  802.         final Field<T> field = julianEpoch.getField();
  803.         return new FieldAbsoluteDate<>(new FieldAbsoluteDate<>(field, timeScales.getJ2000Epoch()),
  804.                                        julianEpoch.subtract(2000.0).multiply(Constants.JULIAN_YEAR));
  805.     }

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

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

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

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

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

  898.     /** Reference epoch for 1950 dates: 1950-01-01T00:00:00 Terrestrial Time.
  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 1950 dates as a FieldAbsoluteDate
  905.      * @see AbsoluteDate#FIFTIES_EPOCH
  906.      * @see TimeScales#getFiftiesEpoch()
  907.      */
  908.     @DefaultDataContext
  909.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> getFiftiesEpoch(final Field<T> field) {
  910.         return new FieldAbsoluteDate<>(field,
  911.                 DataContext.getDefault().getTimeScales().getFiftiesEpoch());
  912.     }

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

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

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

  959.     /** J2000.0 Reference epoch: 2000-01-01T12:00:00 Terrestrial Time (<em>not</em> 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 J2000.0 reference epoch as a FieldAbsoluteDate
  966.      * @see #createJulianEpoch(RealFieldElement)
  967.      * @see AbsoluteDate#J2000_EPOCH
  968.      * @see TimeScales#getJ2000Epoch()
  969.      */
  970.     @DefaultDataContext
  971.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> getJ2000Epoch(final Field<T> field) {
  972.         return new FieldAbsoluteDate<>(field,
  973.                 DataContext.getDefault().getTimeScales().getJ2000Epoch());
  974.     }

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

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

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

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

  1024.         return new FieldAbsoluteDate<>(field, AbsoluteDate.ARBITRARY_EPOCH);
  1025.     }


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

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

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

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

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

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

  1137.     /** Split the instance into date/time components.
  1138.      * @param timeScale time scale to use
  1139.      * @return date/time components
  1140.      */
  1141.     public DateTimeComponents getComponents(final TimeScale timeScale) {

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

  1151.         // compute offset from 2000-01-01T00:00:00 in specified time scale exactly,
  1152.         // using Møller-Knuth TwoSum algorithm without branching
  1153.         // the following statements must NOT be simplified, they rely on floating point
  1154.         // arithmetic properties (rounding and representable numbers)
  1155.         // at the end, the EXACT result of addition offset + timeScale.offsetFromTAI(this)
  1156.         // is sum + residual, where sum is the closest representable number to the exact
  1157.         // result and residual is the missing part that does not fit in the first number
  1158.         final double taiOffset = timeScale.offsetFromTAI(this).getReal();
  1159.         final double sum       = offset.getReal() + taiOffset;
  1160.         final double oPrime    = sum - taiOffset;
  1161.         final double dPrime    = sum - oPrime;
  1162.         final double deltaO    = offset.getReal() - oPrime;
  1163.         final double deltaD    = taiOffset - dPrime;
  1164.         final double residual  = deltaO + deltaD;

  1165.         // split date and time
  1166.         final long   carry = (long) FastMath.floor(sum);
  1167.         double offset2000B = (sum - carry) + residual;
  1168.         long   offset2000A = epoch + carry + 43200l;
  1169.         if (offset2000B < 0) {
  1170.             offset2000A -= 1;
  1171.             offset2000B += 1;
  1172.         }
  1173.         long time = offset2000A % 86400l;
  1174.         if (time < 0l) {
  1175.             time += 86400l;
  1176.         }
  1177.         final int date = (int) ((offset2000A - time) / 86400l);

  1178.         // extract calendar elements
  1179.         final DateComponents dateComponents = new DateComponents(DateComponents.J2000_EPOCH, date);
  1180.         // extract time element, accounting for leap seconds
  1181.         final double leap =
  1182.                 timeScale.insideLeap(this) ? timeScale.getLeap(this.toAbsoluteDate()) : 0;
  1183.         final int minuteDuration = timeScale.minuteDuration(this);
  1184.         final TimeComponents timeComponents =
  1185.                 TimeComponents.fromSeconds((int) time, offset2000B, leap, minuteDuration);

  1186.         // build the components
  1187.         return new DateTimeComponents(dateComponents, timeComponents);

  1188.     }

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

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

  1214.         final DateTimeComponents utcComponents = getComponents(utc);

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

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

  1241.     }

  1242.     /** {@inheritDoc} */
  1243.     public FieldAbsoluteDate<T> getDate() {
  1244.         return this;
  1245.     }

  1246.     /** Get the field.
  1247.      * @return field instance.
  1248.      */
  1249.     public Field<T> getField() {
  1250.         return field;
  1251.     }

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

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

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


  1285.     /** Check if the instance represents the same time as another instance.
  1286.      * @param date other date
  1287.      * @return true if the instance and the other date refer to the same instant
  1288.      */
  1289.     @SuppressWarnings("unchecked")
  1290.     public boolean equals(final Object date) {

  1291.         if (date == this) {
  1292.             // first fast check
  1293.             return true;
  1294.         }

  1295.         if ((date != null) && (date instanceof FieldAbsoluteDate)) {
  1296.             return durationFrom((FieldAbsoluteDate<T>) date).getReal() == 0.0;
  1297.         }

  1298.         return false;

  1299.     }

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

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

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

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

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

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

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

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

  1391.     /** Get a hashcode for this date.
  1392.      * @return hashcode
  1393.      */
  1394.     public int hashCode() {
  1395.         final long l = Double.doubleToLongBits(durationFrom(AbsoluteDate.ARBITRARY_EPOCH).getReal());
  1396.         return (int) (l ^ (l >>> 32));
  1397.     }

  1398.     /** Get a String representation of the instant location in UTC time scale.
  1399.      *
  1400.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  1401.      *
  1402.      * @return a string representation of the instance,
  1403.      * in ISO-8601 format with milliseconds accuracy
  1404.      * @see #toString(TimeScale)
  1405.      */
  1406.     @DefaultDataContext
  1407.     public String toString() {
  1408.         return toString(DataContext.getDefault().getTimeScales().getUTC());
  1409.     }

  1410.     /** Get a String representation of the instant location.
  1411.      * @param timeScale time scale to use
  1412.      * @return a string representation of the instance,
  1413.      * in ISO-8601 format with milliseconds accuracy
  1414.      */
  1415.     public String toString(final TimeScale timeScale) {
  1416.         return getComponents(timeScale).toString(timeScale.minuteDuration(this));
  1417.     }

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

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

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

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

  1473.     /** Get a time-shifted date.
  1474.      * <p>
  1475.      * Calling this method is equivalent to call <code>new AbsoluteDate(this, dt)</code>.
  1476.      * </p>
  1477.      * @param dt time shift in seconds
  1478.      * @return a new date, shifted with respect to instance (which is immutable)
  1479.      * @see org.orekit.utils.PVCoordinates#shiftedBy(double)
  1480.      * @see org.orekit.attitudes.Attitude#shiftedBy(double)
  1481.      * @see org.orekit.orbits.Orbit#shiftedBy(double)
  1482.      * @see org.orekit.propagation.SpacecraftState#shiftedBy(double)
  1483.      */

  1484.     @Override
  1485.     public FieldAbsoluteDate<T> shiftedBy(final double dt) {
  1486.         return new FieldAbsoluteDate<>(this, dt);
  1487.     }


  1488.     /** Transform the FieldAbsoluteDate in an AbsoluteDate.
  1489.      * @return AbsoluteDate of the FieldObject
  1490.      * */
  1491.     public AbsoluteDate toAbsoluteDate() {
  1492.         return new AbsoluteDate(epoch, offset.getReal());
  1493.     }

  1494. }