FieldAbsoluteDate.java

  1. /* Copyright 2002-2019 CS Systèmes d'Information
  2.  * Licensed to CS Systèmes d'Information (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.errors.OrekitException;
  24. import org.orekit.errors.OrekitMessages;
  25. import org.orekit.utils.Constants;

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

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

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

  98.     /** Offset from the reference epoch in seconds. */
  99.     private final  T offset;

  100.     /** Field used by default.*/
  101.     private Field<T> field;

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

  111.     /** Create an instance with a default value ({@link #getJ2000Epoch(Field)}).
  112.      * @param field field used by default
  113.      */
  114.     public FieldAbsoluteDate(final Field<T> field) {
  115.         final FieldAbsoluteDate<T> j2000 = getJ2000Epoch(field);
  116.         this.field  = j2000.field;
  117.         this.epoch  = j2000.epoch;
  118.         this.offset = j2000.offset;
  119.     }

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

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

  176.     /** Build an instance from a location in a {@link TimeScale time scale}.
  177.      * @param field field utilized by default
  178.      * @param location location in the time scale
  179.      * @param timeScale time scale
  180.      */
  181.     public FieldAbsoluteDate(final Field<T> field, final DateTimeComponents location, final TimeScale timeScale) {
  182.         this(field, location.getDate(), location.getTime(), timeScale);
  183.     }

  184.     /** Build an instance from a location in a {@link TimeScale time scale}.
  185.      * @param field field utilized by default
  186.      * @param date date location in the time scale
  187.      * @param time time location in the time scale
  188.      * @param timeScale time scale
  189.      */
  190.     public FieldAbsoluteDate(final Field<T> field, final DateComponents date, final TimeComponents time,
  191.                              final TimeScale timeScale) {
  192.         final double seconds  = time.getSecond();
  193.         final double tsOffset = timeScale.offsetToTAI(date, time);

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

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

  208.         epoch  = 60l * ((date.getJ2000Day() * 24l + time.getHour()) * 60l +
  209.                         time.getMinute() - time.getMinutesFromUTC() - 720l) + dl;
  210.         this.field = field;

  211.     }

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

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

  246.     /** Build an instance from a location in a {@link TimeScale time scale}.
  247.      * <p>The hour is set to 00:00:00.000.</p>
  248.      * @param field field utilized by default
  249.      * @param date date location in the time scale
  250.      * @param timeScale time scale
  251.      * @exception IllegalArgumentException if inconsistent arguments
  252.      * are given (parameters out of range)
  253.      */
  254.     public FieldAbsoluteDate(final Field<T> field, final DateComponents date, final TimeScale timeScale)
  255.         throws IllegalArgumentException {
  256.         this(field, date, TimeComponents.H00, timeScale);
  257.     }

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

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

  286.     /** Build an instance from a location in a {@link TimeScale time scale}.
  287.      * @param field field utilized as default
  288.      * @param location location in the time scale
  289.      * @param timeScale time scale
  290.      */
  291.     public FieldAbsoluteDate(final Field<T> field, final Date location, final TimeScale timeScale) {
  292.         this(field, new DateComponents(DateComponents.JAVA_EPOCH,
  293.                                 (int) (location.getTime() / 86400000l)),
  294.                                 new TimeComponents(0.001 * (location.getTime() % 86400000l)),
  295.              timeScale);
  296.     }


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


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

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

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

  367.     /** Build an instance from a CCSDS Unsegmented Time Code (CUC).
  368.      * <p>
  369.      * CCSDS Unsegmented Time Code is defined in the blue book:
  370.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  371.      * </p>
  372.      * <p>
  373.      * If the date to be parsed is formatted using version 3 of the standard
  374.      * (CCSDS 301.0-B-3 published in 2002) or if the extension of the preamble
  375.      * field introduced in version 4 of the standard is not used, then the
  376.      * {@code preambleField2} parameter can be set to 0.
  377.      * </p>
  378.      * @param field field for the components
  379.      * @param preambleField1 first byte of the field specifying the format, often
  380.      * not transmitted in data interfaces, as it is constant for a given data interface
  381.      * @param preambleField2 second byte of the field specifying the format
  382.      * (added in revision 4 of the CCSDS standard in 2010), often not transmitted in data
  383.      * interfaces, as it is constant for a given data interface (value ignored if presence
  384.      * not signaled in {@code preambleField1})
  385.      * @param timeField byte array containing the time code
  386.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  387.      * specifies the {@link #getCCSDSEpoch(Field) CCSDS reference epoch} is used (and hence
  388.      * may be null in this case)
  389.      * @return an instance corresponding to the specified date
  390.      * @param <T> the type of the field elements
  391.      */
  392.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> parseCCSDSUnsegmentedTimeCode(final Field<T> field,
  393.                                                                                                      final byte preambleField1,
  394.                                                                                                      final byte preambleField2,
  395.                                                                                                      final byte[] timeField,
  396.                                                                                                      final FieldAbsoluteDate<T> agencyDefinedEpoch) {

  397.         // time code identification and reference epoch
  398.         final FieldAbsoluteDate<T> epochF;
  399.         switch (preambleField1 & 0x70) {
  400.             case 0x10:
  401.                 // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  402.                 epochF = getCCSDSEpoch(field);
  403.                 break;
  404.             case 0x20:
  405.                 // the reference epoch is agency defined
  406.                 if (agencyDefinedEpoch == null) {
  407.                     throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  408.                 }
  409.                 epochF = agencyDefinedEpoch;
  410.                 break;
  411.             default :
  412.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  413.                                           formatByte(preambleField1));
  414.         }

  415.         // time field lengths
  416.         int coarseTimeLength = 1 + ((preambleField1 & 0x0C) >>> 2);
  417.         int fineTimeLength   = preambleField1 & 0x03;

  418.         if ((preambleField1 & 0x80) != 0x0) {
  419.             // there is an additional octet in preamble field
  420.             coarseTimeLength += (preambleField2 & 0x60) >>> 5;
  421.             fineTimeLength   += (preambleField2 & 0x1C) >>> 2;
  422.         }

  423.         if (timeField.length != coarseTimeLength + fineTimeLength) {
  424.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  425.                                       timeField.length, coarseTimeLength + fineTimeLength);
  426.         }

  427.         T seconds = field.getZero();
  428.         for (int i = 0; i < coarseTimeLength; ++i) {
  429.             seconds = seconds.multiply(256).add(field.getZero().add(toUnsigned(timeField[i])));
  430.         }
  431.         T subseconds = field.getZero();
  432.         for (int i = timeField.length - 1; i >= coarseTimeLength; --i) {
  433.             subseconds = (subseconds.add(toUnsigned(timeField[i]))).divide(256);
  434.         }
  435.         return new FieldAbsoluteDate<>(epochF, seconds).shiftedBy(subseconds);

  436.     }

  437.     /** Build an instance from a CCSDS Day Segmented Time Code (CDS).
  438.      * <p>
  439.      * CCSDS Day Segmented Time Code is defined in the blue book:
  440.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  441.      * </p>
  442.      * @param field field for the components
  443.      * @param preambleField field specifying the format, often not transmitted in
  444.      * data interfaces, as it is constant for a given data interface
  445.      * @param timeField byte array containing the time code
  446.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  447.      * specifies the {@link #getCCSDSEpoch(Field) CCSDS reference epoch} is used (and hence
  448.      * may be null in this case)
  449.      * @return an instance corresponding to the specified date
  450.      * @param <T> the type of the field elements
  451.      */
  452.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> parseCCSDSDaySegmentedTimeCode(final Field<T> field,
  453.                                                                                                       final byte preambleField, final byte[] timeField,
  454.                                                                                                       final DateComponents agencyDefinedEpoch) {

  455.         // time code identification
  456.         if ((preambleField & 0xF0) != 0x40) {
  457.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  458.                                       formatByte(preambleField));
  459.         }

  460.         // reference epoch
  461.         final DateComponents epochDC;
  462.         if ((preambleField & 0x08) == 0x00) {
  463.             // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  464.             epochDC = DateComponents.CCSDS_EPOCH;
  465.         } else {
  466.             // the reference epoch is agency defined
  467.             if (agencyDefinedEpoch == null) {
  468.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  469.             }
  470.             epochDC = agencyDefinedEpoch;
  471.         }

  472.         // time field lengths
  473.         final int daySegmentLength = ((preambleField & 0x04) == 0x0) ? 2 : 3;
  474.         final int subMillisecondLength = (preambleField & 0x03) << 1;
  475.         if (subMillisecondLength == 6) {
  476.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  477.                                       formatByte(preambleField));
  478.         }
  479.         if (timeField.length != daySegmentLength + 4 + subMillisecondLength) {
  480.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  481.                                       timeField.length, daySegmentLength + 4 + subMillisecondLength);
  482.         }


  483.         int i   = 0;
  484.         int day = 0;
  485.         while (i < daySegmentLength) {
  486.             day = day * 256 + toUnsigned(timeField[i++]);
  487.         }

  488.         long milliInDay = 0l;
  489.         while (i < daySegmentLength + 4) {
  490.             milliInDay = milliInDay * 256 + toUnsigned(timeField[i++]);
  491.         }
  492.         final int milli   = (int) (milliInDay % 1000l);
  493.         final int seconds = (int) ((milliInDay - milli) / 1000l);

  494.         double subMilli = 0;
  495.         double divisor  = 1;
  496.         while (i < timeField.length) {
  497.             subMilli = subMilli * 256 + toUnsigned(timeField[i++]);
  498.             divisor *= 1000;
  499.         }

  500.         final DateComponents date = new DateComponents(epochDC, day);
  501.         final TimeComponents time = new TimeComponents(seconds);
  502.         return new FieldAbsoluteDate<>(field, date, time, TimeScalesFactory.getUTC()).shiftedBy(milli * 1.0e-3 + subMilli / divisor);

  503.     }

  504.     /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  505.      * <p>
  506.      * CCSDS Calendar Segmented Time Code is defined in the blue book:
  507.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  508.      * </p>
  509.      * @param preambleField field specifying the format, often not transmitted in
  510.      * data interfaces, as it is constant for a given data interface
  511.      * @param timeField byte array containing the time code
  512.      * @return an instance corresponding to the specified date
  513.      */
  514.     public FieldAbsoluteDate<T> parseCCSDSCalendarSegmentedTimeCode(final byte preambleField, final byte[] timeField) {

  515.         // time code identification
  516.         if ((preambleField & 0xF0) != 0x50) {
  517.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  518.                                       formatByte(preambleField));
  519.         }

  520.         // time field length
  521.         final int length = 7 + (preambleField & 0x07);
  522.         if (length == 14) {
  523.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  524.                                       formatByte(preambleField));
  525.         }
  526.         if (timeField.length != length) {
  527.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  528.                                       timeField.length, length);
  529.         }

  530.         // date part in the first four bytes
  531.         final DateComponents date;
  532.         if ((preambleField & 0x08) == 0x00) {
  533.             // month of year and day of month variation
  534.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  535.                                       toUnsigned(timeField[2]),
  536.                                       toUnsigned(timeField[3]));
  537.         } else {
  538.             // day of year variation
  539.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  540.                                       toUnsigned(timeField[2]) * 256 + toUnsigned(timeField[3]));
  541.         }

  542.         // time part from bytes 5 to last (between 7 and 13 depending on precision)
  543.         final TimeComponents time = new TimeComponents(toUnsigned(timeField[4]),
  544.                                                        toUnsigned(timeField[5]),
  545.                                                        toUnsigned(timeField[6]));
  546.         double subSecond = 0;
  547.         double divisor   = 1;
  548.         for (int i = 7; i < length; ++i) {
  549.             subSecond = subSecond * 100 + toUnsigned(timeField[i]);
  550.             divisor *= 100;
  551.         }

  552.         return new FieldAbsoluteDate<>(field, date, time, TimeScalesFactory.getUTC()).shiftedBy(subSecond / divisor);

  553.     }

  554.     /** Decode a signed byte as an unsigned int value.
  555.      * @param b byte to decode
  556.      * @return an unsigned int value
  557.      */
  558.     private static int toUnsigned(final byte b) {
  559.         final int i = (int) b;
  560.         return (i < 0) ? 256 + i : i;
  561.     }

  562.     /** Format a byte as an hex string for error messages.
  563.      * @param data byte to format
  564.      * @return a formatted string
  565.      */
  566.     private static String formatByte(final byte data) {
  567.         return "0x" + Integer.toHexString(data).toUpperCase();
  568.     }

  569.     /** Build an instance corresponding to a Julian Day date.
  570.      * @param jd Julian day
  571.      * @param secondsSinceNoon seconds in the Julian day
  572.      * (BEWARE, Julian days start at noon, so 0.0 is noon)
  573.      * @param timeScale time scale in which the seconds in day are defined
  574.      * @return a new instant
  575.      * @param <T> the type of the field elements
  576.      */
  577.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> createJDDate(final int jd, final T secondsSinceNoon,
  578.                                                                                     final TimeScale timeScale) {
  579.         return new FieldAbsoluteDate<>(secondsSinceNoon.getField(), new DateComponents(DateComponents.JULIAN_EPOCH, jd),
  580.                                        TimeComponents.H12, timeScale).shiftedBy(secondsSinceNoon);
  581.     }

  582.     /** Build an instance corresponding to a Modified Julian Day date.
  583.      * @param mjd modified Julian day
  584.      * @param secondsInDay seconds in the day
  585.      * @param timeScale time scale in which the seconds in day are defined
  586.      * @return a new instant
  587.      * @param <T> the type of the field elements
  588.      */
  589.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> createMJDDate(final int mjd, final T secondsInDay,
  590.                                                                                      final TimeScale timeScale) {
  591.         return new FieldAbsoluteDate<>(secondsInDay.getField(),
  592.                                        new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, mjd),
  593.                                        TimeComponents.H00,
  594.                                        timeScale).shiftedBy(secondsInDay);
  595.     }

  596.     /** Build an instance corresponding to a GPS date.
  597.      * <p>GPS dates are provided as a week number starting at
  598.      * {@link #getGPSEpoch(Field) GPS epoch} and as a number of milliseconds
  599.      * since week start.</p>
  600.      * @param weekNumber week number since {@link #getGPSEpoch(Field) GPS epoch}
  601.      * @param milliInWeek number of milliseconds since week start
  602.      * @return a new instant
  603.      * @param <T> the type of the field elements
  604.      */
  605.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> createGPSDate(final int weekNumber, final T milliInWeek) {
  606.         final int day = (int) FastMath.floor(milliInWeek.getReal() / (1000.0 * Constants.JULIAN_DAY));
  607.         final T secondsInDay = milliInWeek.divide(1000.0).subtract(day * Constants.JULIAN_DAY);
  608.         return new FieldAbsoluteDate<>(milliInWeek.getField(), new DateComponents(DateComponents.GPS_EPOCH, weekNumber * 7 + day),
  609.                                        TimeComponents.H00, TimeScalesFactory.getGPS()).shiftedBy(secondsInDay);
  610.     }

  611.     /** Build an instance corresponding to a Julian Epoch (JE).
  612.      * <p>According to Lieske paper: <a
  613.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&amp;defaultprint=YES&amp;filetype=.pdf.">
  614.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
  615.      * vol. 73, no. 3, Mar. 1979, p. 282-284, Julian Epoch is related to Julian Ephemeris Date as:</p>
  616.      * <pre>
  617.      * JE = 2000.0 + (JED - 2451545.0) / 365.25
  618.      * </pre>
  619.      * <p>
  620.      * This method reverts the formula above and computes an {@code FieldAbsoluteDate<T>} from the Julian Epoch.
  621.      * </p>
  622.      * @param julianEpoch Julian epoch, like 2000.0 for defining the classical reference J2000.0
  623.      * @return a new instant
  624.      * @see #getJ2000Epoch(Field)
  625.      * @see #createBesselianEpoch(RealFieldElement)
  626.      * @param <T> the type of the field elements
  627.      */
  628.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> createJulianEpoch(final T julianEpoch) {
  629.         return new FieldAbsoluteDate<>(getJ2000Epoch(julianEpoch.getField()),
  630.                                        julianEpoch.subtract(2000.0).multiply(Constants.JULIAN_YEAR));
  631.     }

  632.     /** Build an instance corresponding to a Besselian Epoch (BE).
  633.      * <p>According to Lieske paper: <a
  634.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&amp;defaultprint=YES&amp;filetype=.pdf.">
  635.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
  636.      * vol. 73, no. 3, Mar. 1979, p. 282-284, Besselian Epoch is related to Julian Ephemeris Date as:</p>
  637.      * <pre>
  638.      * BE = 1900.0 + (JED - 2415020.31352) / 365.242198781
  639.      * </pre>
  640.      * <p>
  641.      * This method reverts the formula above and computes an {@code FieldAbsoluteDate<T>} from the Besselian Epoch.
  642.      * </p>
  643.      * @param besselianEpoch Besselian epoch, like 1950 for defining the classical reference B1950.0
  644.      * @return a new instant
  645.      * @see #createJulianEpoch(RealFieldElement)
  646.      * @param <T> the type of the field elements
  647.      */
  648.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> createBesselianEpoch(final T besselianEpoch) {
  649.         return new FieldAbsoluteDate<>(getJ2000Epoch(besselianEpoch.getField()),
  650.                                        besselianEpoch.subtract(1900).multiply(Constants.BESSELIAN_YEAR).add(
  651.                                        Constants.JULIAN_DAY * (-36525) + Constants.JULIAN_DAY * 0.31352));
  652.     }

  653.     /** Reference epoch for julian dates: -4712-01-01T12:00:00 Terrestrial Time.
  654.      * <p>Both <code>java.util.Date</code> and {@link DateComponents} classes
  655.      * follow the astronomical conventions and consider a year 0 between
  656.      * years -1 and +1, hence this reference date lies in year -4712 and not
  657.      * in year -4713 as can be seen in other documents or programs that obey
  658.      * a different convention (for example the <code>convcal</code> utility).</p>
  659.      * @param field field for the components
  660.      * @return FieldAbsoluteDate<T> FieldAbsoluteDate<T> representing {@link AbsoluteDate#JULIAN_EPOCH}
  661.      * @param <T> the type of the field elements
  662.      */
  663.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> getJulianEpoch(final Field<T> field) {
  664.         return new FieldAbsoluteDate<>(field, AbsoluteDate.JULIAN_EPOCH);
  665.     }

  666.     /** Reference epoch for modified julian dates: 1858-11-17T00:00:00 Terrestrial Time.
  667.      * @param field field for the components
  668.      * @return FieldAbsoluteDate<T> FieldAbsoluteDate<T> representing {@link AbsoluteDate#MODIFIED_JULIAN_EPOCH}
  669.      * @param <T> the type of the field elements
  670.      */
  671.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> getModifiedJulianEpoch(final Field<T> field) {
  672.         return new FieldAbsoluteDate<>(field, AbsoluteDate.MODIFIED_JULIAN_EPOCH);
  673.     }

  674.     /** Reference epoch for 1950 dates: 1950-01-01T00:00:00 Terrestrial Time.
  675.      * @param field field for the components
  676.      * @return FieldAbsoluteDate<T> FieldAbsoluteDate<T> representing {@link AbsoluteDate#FIFTIES_EPOCH}
  677.      * @param <T> the type of the field elements
  678.      */
  679.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> getFiftiesEpoch(final Field<T> field) {
  680.         return new FieldAbsoluteDate<>(field, AbsoluteDate.FIFTIES_EPOCH);
  681.     }
  682.     /** Reference epoch for CCSDS Time Code Format (CCSDS 301.0-B-4):
  683.      * 1958-01-01T00:00:00 International Atomic Time (<em>not</em> UTC).
  684.      * @param field field for the components
  685.      * @return FieldAbsoluteDate<T> FieldAbsoluteDate<T> representing {@link AbsoluteDate#CCSDS_EPOCH}
  686.      * @param <T> the type of the field elements
  687.      */
  688.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> getCCSDSEpoch(final Field<T> field) {
  689.         return new FieldAbsoluteDate<>(field, AbsoluteDate.CCSDS_EPOCH);
  690.     }

  691.     /** Reference epoch for Galileo System Time: 1999-08-22T00:00:00 UTC.
  692.      * @param field field for the components
  693.      * @return FieldAbsoluteDate<T> FieldAbsoluteDate<T> representing {@link AbsoluteDate#GALILEO_EPOCH}
  694.      * @param <T> the type of the field elements
  695.      */
  696.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> getGalileoEpoch(final Field<T> field) {
  697.         return new FieldAbsoluteDate<>(field, AbsoluteDate.GALILEO_EPOCH);
  698.     }

  699.     /** Reference epoch for GPS weeks: 1980-01-06T00:00:00 GPS time.
  700.      * @param field field for the components
  701.      * @return FieldAbsoluteDate<T> FieldAbsoluteDate<T> representing {@link AbsoluteDate#GPS_EPOCH}
  702.      * @param <T> the type of the field elements
  703.      */
  704.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> getGPSEpoch(final Field<T> field) {
  705.         return new FieldAbsoluteDate<>(field, AbsoluteDate.GPS_EPOCH);
  706.     }

  707.     /** J2000.0 Reference epoch: 2000-01-01T12:00:00 Terrestrial Time (<em>not</em> UTC).
  708.      * @param field field for the components
  709.      * @see #createJulianEpoch(RealFieldElement)
  710.      * @see #createBesselianEpoch(RealFieldElement)
  711.      * @return FieldAbsoluteDate<T> FieldAbsoluteDate<T> representing {@link AbsoluteDate#J2000_EPOCH}
  712.      * @param <T> the type of the field elements
  713.      */
  714.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> getJ2000Epoch(final Field<T> field) {
  715.         return new FieldAbsoluteDate<>(field, AbsoluteDate.J2000_EPOCH);
  716.     }

  717.     /** Java Reference epoch: 1970-01-01T00:00:00 Universal Time Coordinate.
  718.      * <p>
  719.      * Between 1968-02-01 and 1972-01-01, UTC-TAI = 4.213 170 0s + (MJD - 39 126) x 0.002 592s.
  720.      * As on 1970-01-01 MJD = 40587, UTC-TAI = 8.000082s
  721.      * </p>
  722.      * @param field field for the components
  723.      * @return FieldAbsoluteDate<T> FieldAbsoluteDate<T> representing {@link AbsoluteDate#JAVA_EPOCH}
  724.      * @param <T> the type of the field elements
  725.      */
  726.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> getJavaEpoch(final Field<T> field) {
  727.         return new FieldAbsoluteDate<>(field, AbsoluteDate.JAVA_EPOCH);
  728.     }

  729.     /** Dummy date at infinity in the past direction.
  730.      * @param field field for the components
  731.      * @return FieldAbsoluteDate<T> FieldAbsoluteDate<T> representing {@link AbsoluteDate#PAST_INFINITY}
  732.      * @param <T> the type of the field elements
  733.      */
  734.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> getPastInfinity(final Field<T> field) {
  735.         return new FieldAbsoluteDate<>(field, AbsoluteDate.PAST_INFINITY);
  736.     }

  737.     /** Dummy date at infinity in the future direction.
  738.      * @param field field for the components
  739.      * @return FieldAbsoluteDate<T> FieldAbsoluteDate<T> representing {@link AbsoluteDate#FUTURE_INFINITY}
  740.      * @param <T> the type of the field elements
  741.      */
  742.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> getFutureInfinity(final Field<T> field) {
  743.         return new FieldAbsoluteDate<>(field, AbsoluteDate.FUTURE_INFINITY);
  744.     }

  745.     /** Get a time-shifted date.
  746.      * <p>
  747.      * Calling this method is equivalent to call {@code new FieldAbsoluteDate&lt;&gt;(this, dt)}.
  748.      * </p>
  749.      * @param dt time shift in seconds
  750.      * @return a new date, shifted with respect to instance (which is immutable)
  751.      * @see org.orekit.utils.PVCoordinates#shiftedBy(double)
  752.      * @see org.orekit.attitudes.Attitude#shiftedBy(double)
  753.      * @see org.orekit.orbits.Orbit#shiftedBy(double)
  754.      * @see org.orekit.propagation.SpacecraftState#shiftedBy(double)
  755.      */
  756.     public FieldAbsoluteDate<T> shiftedBy(final T dt) {
  757.         return new FieldAbsoluteDate<>(this, dt);
  758.     }

  759.     /** Compute the physically elapsed duration between two instants.
  760.      * <p>The returned duration is the number of seconds physically
  761.      * elapsed between the two instants, measured in a regular time
  762.      * scale with respect to surface of the Earth (i.e either the {@link
  763.      * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
  764.      * GPSScale GPS scale}). It is the only method that gives a
  765.      * duration with a physical meaning.</p>
  766.      * <p>This method gives the same result (with less computation)
  767.      * as calling {@link #offsetFrom(FieldAbsoluteDate, TimeScale)}
  768.      * with a second argument set to one of the regular scales cited
  769.      * above.</p>
  770.      * <p>This method is the reverse of the {@link #FieldAbsoluteDate(FieldAbsoluteDate,
  771.      * double)} constructor.</p>
  772.      * @param instant instant to subtract from the instance
  773.      * @return offset in seconds between the two instants (positive
  774.      * if the instance is posterior to the argument)
  775.      * @see #offsetFrom(FieldAbsoluteDate, TimeScale)
  776.      * @see #FieldAbsoluteDate(FieldAbsoluteDate, double)
  777.      */
  778.     public T durationFrom(final FieldAbsoluteDate<T> instant) {
  779.         return offset.subtract(instant.offset).add(epoch - instant.epoch);
  780.     }

  781.     /** Compute the physically elapsed duration between two instants.
  782.      * <p>The returned duration is the number of seconds physically
  783.      * elapsed between the two instants, measured in a regular time
  784.      * scale with respect to surface of the Earth (i.e either the {@link
  785.      * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
  786.      * GPSScale GPS scale}). It is the only method that gives a
  787.      * duration with a physical meaning.</p>
  788.      * <p>This method gives the same result (with less computation)
  789.      * as calling {@link #offsetFrom(FieldAbsoluteDate, TimeScale)}
  790.      * with a second argument set to one of the regular scales cited
  791.      * above.</p>
  792.      * <p>This method is the reverse of the {@link #FieldAbsoluteDate(FieldAbsoluteDate,
  793.      * double)} constructor.</p>
  794.      * @param instant instant to subtract from the instance
  795.      * @return offset in seconds between the two instants (positive
  796.      * if the instance is posterior to the argument)
  797.      * @see #offsetFrom(FieldAbsoluteDate, TimeScale)
  798.      * @see #FieldAbsoluteDate(FieldAbsoluteDate, double)
  799.      */
  800.     public T durationFrom(final AbsoluteDate instant) {
  801.         return offset.subtract(instant.getOffset()).add(epoch - instant.getEpoch());
  802.     }

  803.     /** Compute the apparent clock offset between two instant <em>in the
  804.      * perspective of a specific {@link TimeScale time scale}</em>.
  805.      * <p>The offset is the number of seconds counted in the given
  806.      * time scale between the locations of the two instants, with
  807.      * all time scale irregularities removed (i.e. considering all
  808.      * days are exactly 86400 seconds long). This method will give
  809.      * a result that may not have a physical meaning if the time scale
  810.      * is irregular. For example since a leap second was introduced at
  811.      * the end of 2005, the apparent offset between 2005-12-31T23:59:59
  812.      * and 2006-01-01T00:00:00 is 1 second, but the physical duration
  813.      * of the corresponding time interval as returned by the {@link
  814.      * #durationFrom(FieldAbsoluteDate)} method is 2 seconds.</p>
  815.      * <p>This method is the reverse of the {@link #FieldAbsoluteDate(FieldAbsoluteDate,
  816.      * double, TimeScale)} constructor.</p>
  817.      * @param instant instant to subtract from the instance
  818.      * @param timeScale time scale with respect to which the offset should
  819.      * be computed
  820.      * @return apparent clock offset in seconds between the two instants
  821.      * (positive if the instance is posterior to the argument)
  822.      * @see #durationFrom(FieldAbsoluteDate)
  823.      * @see #FieldAbsoluteDate(FieldAbsoluteDate, double, TimeScale)
  824.      */
  825.     public T offsetFrom(final FieldAbsoluteDate<T> instant, final TimeScale timeScale) {
  826.         final long   elapsedDurationA = epoch - instant.epoch;
  827.         final T elapsedDurationB = offset.add(timeScale.offsetFromTAI(this)).
  828.                                    subtract(instant.offset.add(timeScale.offsetFromTAI(instant)));
  829.         return  elapsedDurationB.add(elapsedDurationA);
  830.     }

  831.     /** Compute the offset between two time scales at the current instant.
  832.      * <p>The offset is defined as <i>l₁-l₂</i>
  833.      * where <i>l₁</i> is the location of the instant in
  834.      * the <code>scale1</code> time scale and <i>l₂</i> is the
  835.      * location of the instant in the <code>scale2</code> time scale.</p>
  836.      * @param scale1 first time scale
  837.      * @param scale2 second time scale
  838.      * @return offset in seconds between the two time scales at the
  839.      * current instant
  840.      */
  841.     public T timeScalesOffset(final TimeScale scale1, final TimeScale scale2) {
  842.         return scale1.offsetFromTAI(this).subtract(scale2.offsetFromTAI(this));
  843.     }

  844.     /** Convert the instance to a Java {@link java.util.Date Date}.
  845.      * <p>Conversion to the Date class induces a loss of precision because
  846.      * the Date class does not provide sub-millisecond information. Java Dates
  847.      * are considered to be locations in some times scales.</p>
  848.      * @param timeScale time scale to use
  849.      * @return a {@link java.util.Date Date} instance representing the location
  850.      * of the instant in the time scale
  851.      */
  852.     public Date toDate(final TimeScale timeScale) {
  853.         final double time = epoch + (offset.getReal() + timeScale.offsetFromTAI(this).getReal());
  854.         return new Date(FastMath.round((time + 10957.5 * 86400.0) * 1000));
  855.     }

  856.     /** Split the instance into date/time components.
  857.      * @param timeScale time scale to use
  858.      * @return date/time components
  859.      */
  860.     public DateTimeComponents getComponents(final TimeScale timeScale) {

  861.         if (Double.isInfinite(offset.getReal())) {
  862.             // special handling for past and future infinity
  863.             if (offset.getReal() < 0) {
  864.                 return new DateTimeComponents(DateComponents.MIN_EPOCH, TimeComponents.H00);
  865.             } else {
  866.                 return new DateTimeComponents(DateComponents.MAX_EPOCH,
  867.                                               new TimeComponents(23, 59, 59.999));
  868.             }
  869.         }

  870.         // compute offset from 2000-01-01T00:00:00 in specified time scale exactly,
  871.         // using Møller-Knuth TwoSum algorithm without branching
  872.         // the following statements must NOT be simplified, they rely on floating point
  873.         // arithmetic properties (rounding and representable numbers)
  874.         // at the end, the EXACT result of addition offset + timeScale.offsetFromTAI(this)
  875.         // is sum + residual, where sum is the closest representable number to the exact
  876.         // result and residual is the missing part that does not fit in the first number
  877.         final double taiOffset = timeScale.offsetFromTAI(this).getReal();
  878.         final double sum       = offset.getReal() + taiOffset;
  879.         final double oPrime    = sum - taiOffset;
  880.         final double dPrime    = sum - oPrime;
  881.         final double deltaO    = offset.getReal() - oPrime;
  882.         final double deltaD    = taiOffset - dPrime;
  883.         final double residual  = deltaO + deltaD;

  884.         // split date and time
  885.         final long   carry = (long) FastMath.floor(sum);
  886.         double offset2000B = (sum - carry) + residual;
  887.         long   offset2000A = epoch + carry + 43200l;
  888.         if (offset2000B < 0) {
  889.             offset2000A -= 1;
  890.             offset2000B += 1;
  891.         }
  892.         long time = offset2000A % 86400l;
  893.         if (time < 0l) {
  894.             time += 86400l;
  895.         }
  896.         final int date = (int) ((offset2000A - time) / 86400l);

  897.         // extract calendar elements
  898.         final DateComponents dateComponents = new DateComponents(DateComponents.J2000_EPOCH, date);
  899.         TimeComponents timeComponents = new TimeComponents((int) time, offset2000B);

  900.         if (timeScale.insideLeap(this)) {
  901.             // fix the seconds number to take the leap into account
  902.             timeComponents = new TimeComponents(timeComponents.getHour(), timeComponents.getMinute(),
  903.                                                 timeComponents.getSecond() + timeScale.getLeap(this).getReal());
  904.         }

  905.         // build the components
  906.         return new DateTimeComponents(dateComponents, timeComponents);

  907.     }

  908.     /** Split the instance into date/time components for a local time.
  909.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  910.      * negative Westward UTC)
  911.      * @return date/time components
  912.      */
  913.     public DateTimeComponents getComponents(final int minutesFromUTC) {

  914.         final DateTimeComponents utcComponents = getComponents(TimeScalesFactory.getUTC());

  915.         // shift the date according to UTC offset, but WITHOUT touching the seconds,
  916.         // as they may exceed 60.0 during a leap seconds introduction,
  917.         // and we want to preserve these special cases
  918.         final double seconds = utcComponents.getTime().getSecond();
  919.         int minute = utcComponents.getTime().getMinute() + minutesFromUTC;
  920.         final int hourShift;
  921.         if (minute < 0) {
  922.             hourShift = (minute - 59) / 60;
  923.         } else if (minute > 59) {
  924.             hourShift = minute / 60;
  925.         } else {
  926.             hourShift = 0;
  927.         }
  928.         minute -= 60 * hourShift;
  929.         int hour = utcComponents.getTime().getHour() + hourShift;
  930.         final int dayShift;
  931.         if (hour < 0) {
  932.             dayShift = (hour - 23) / 24;
  933.         } else if (hour > 23) {
  934.             dayShift = hour / 24;
  935.         } else {
  936.             dayShift = 0;
  937.         }
  938.         hour -= 24 * dayShift;

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

  941.     }

  942.     /** {@inheritDoc} */
  943.     public FieldAbsoluteDate<T> getDate() {
  944.         return this;
  945.     }

  946.     /** Get the field.
  947.      * @return field instance.
  948.      */
  949.     public Field<T> getField() {
  950.         return field;
  951.     }

  952.     /** Split the instance into date/time components for a time zone.
  953.      * @param timeZone time zone
  954.      * @return date/time components
  955.      */
  956.     public DateTimeComponents getComponents( final TimeZone timeZone) {
  957.         final long milliseconds = FastMath.round((offsetFrom(getJavaEpoch(field), TimeScalesFactory.getUTC()).getReal()) * 1000);
  958.         return getComponents(timeZone.getOffset(milliseconds) / 60000);
  959.     }

  960.     /** Compare the instance with another date.
  961.      * @param date other date to compare the instance to
  962.      * @return a negative integer, zero, or a positive integer as this date
  963.      * is before, simultaneous, or after the specified date.
  964.      */
  965.     public int compareTo(final FieldAbsoluteDate<T> date) {
  966.         return Double.compare(durationFrom(date).getReal(), 0.0);
  967.     }


  968.     /** Check if the instance represent the same time as another instance.
  969.      * @param date other date
  970.      * @return true if the instance and the other date refer to the same instant
  971.      */
  972.     @SuppressWarnings("unchecked")
  973.     public boolean equals(final Object date) {

  974.         if (date == this) {
  975.             // first fast check
  976.             return true;
  977.         }

  978.         if ((date != null) && (date instanceof FieldAbsoluteDate)) {
  979.             return durationFrom((FieldAbsoluteDate<T>) date).getReal() == 0.0;
  980.         }

  981.         return false;

  982.     }

  983.     /** Get a hashcode for this date.
  984.      * @return hashcode
  985.      */
  986.     public int hashCode() {
  987.         final long l = Double.doubleToLongBits(durationFrom(AbsoluteDate.J2000_EPOCH).getReal());
  988.         return (int) (l ^ (l >>> 32));
  989.     }

  990.     /** Get a String representation of the instant location in UTC time scale.
  991.      * @return a string representation of the instance,
  992.      * in ISO-8601 format with milliseconds accuracy
  993.      */
  994.     public String toString() {
  995.         return toString(TimeScalesFactory.getUTC());
  996.     }

  997.     /** Get a String representation of the instant location.
  998.      * @param timeScale time scale to use
  999.      * @return a string representation of the instance,
  1000.      * in ISO-8601 format with milliseconds accuracy
  1001.      */
  1002.     public String toString(final TimeScale timeScale) {
  1003.         return getComponents(timeScale).toString(timeScale.minuteDuration(this));
  1004.     }

  1005.     /** Get a String representation of the instant location for a local time.
  1006.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1007.      * negative Westward UTC).
  1008.      * @return string representation of the instance,
  1009.      * in ISO-8601 format with milliseconds accuracy
  1010.      */
  1011.     public String toString(final int minutesFromUTC) {
  1012.         final int minuteDuration = TimeScalesFactory.getUTC().minuteDuration(this);
  1013.         return getComponents(minutesFromUTC).toString(minuteDuration);
  1014.     }

  1015.     /** Get a String representation of the instant location for a time zone.
  1016.      * @param timeZone time zone
  1017.      * @return string representation of the instance,
  1018.      * in ISO-8601 format with milliseconds accuracy
  1019.      */
  1020.     public String toString(final TimeZone timeZone) {
  1021.         final int minuteDuration = TimeScalesFactory.getUTC().minuteDuration(this);
  1022.         return getComponents(timeZone).toString(minuteDuration);
  1023.     }

  1024.     /** Get a time-shifted date.
  1025.      * <p>
  1026.      * Calling this method is equivalent to call <code>new AbsoluteDate(this, dt)</code>.
  1027.      * </p>
  1028.      * @param dt time shift in seconds
  1029.      * @return a new date, shifted with respect to instance (which is immutable)
  1030.      * @see org.orekit.utils.PVCoordinates#shiftedBy(double)
  1031.      * @see org.orekit.attitudes.Attitude#shiftedBy(double)
  1032.      * @see org.orekit.orbits.Orbit#shiftedBy(double)
  1033.      * @see org.orekit.propagation.SpacecraftState#shiftedBy(double)
  1034.      */

  1035.     @Override
  1036.     public FieldAbsoluteDate<T> shiftedBy(final double dt) {
  1037.         return new FieldAbsoluteDate<>(this, dt);
  1038.     }


  1039.     /** Transform the FieldAbsoluteDate in an AbsoluteDate.
  1040.      * @return AbsoluteDate of the FieldObject
  1041.      * */
  1042.     public AbsoluteDate toAbsoluteDate() {
  1043.         return new AbsoluteDate(epoch, offset.getReal());
  1044.     }

  1045. }