FieldAbsoluteDate.java

  1. /* Copyright 2002-2018 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<T> date = new FieldAbsoluteDate<>(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.field = since.field;
  306.         final T sum = since.offset.add(elapsedDuration);
  307.         if (Double.isInfinite(sum.getReal())) {
  308.             offset = sum;
  309.             epoch  = (sum.getReal() < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
  310.         } else {
  311.             // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
  312.             // the following statements must NOT be simplified, they rely on floating point
  313.             // arithmetic properties (rounding and representable numbers)
  314.             // at the end, the EXACT result of addition since.offset + elapsedDuration
  315.             // is sum + residual, where sum is the closest representable number to the exact
  316.             // result and residual is the missing part that does not fit in the first number
  317.             final double oPrime   = sum.getReal() - elapsedDuration;
  318.             final double dPrime   = sum.getReal() - oPrime;
  319.             final double deltaO   = since.offset.getReal() - oPrime;
  320.             final double deltaD   = elapsedDuration - dPrime;
  321.             final double residual = deltaO + deltaD;
  322.             final long   dl       = (long) FastMath.floor(sum.getReal());
  323.             offset = sum.subtract(dl).add(residual);
  324.             epoch  = since.epoch + dl;
  325.         }
  326.     }


  327.     /** Build an instance from an elapsed duration since to another instant.
  328.      * <p>It is important to note that the elapsed duration is <em>not</em>
  329.      * the difference between two readings on a time scale.
  330.      * @param since start instant of the measured duration
  331.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  332.      * instant, as measured in a regular time scale
  333.      */
  334.     public FieldAbsoluteDate(final AbsoluteDate since, final T elapsedDuration) {
  335.         this.field = elapsedDuration.getField();
  336.         final double dT = since.durationFrom(AbsoluteDate.J2000_EPOCH);
  337.         final T deltaT = elapsedDuration.add(dT);
  338.         final FieldAbsoluteDate<T> j2000 =  getJ2000Epoch(elapsedDuration.getField()).shiftedBy(deltaT);
  339.         offset = j2000.offset;
  340.         epoch = j2000.epoch;
  341.     }

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

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

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

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

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

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

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

  435.     }

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

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

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

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


  486.         int i   = 0;
  487.         int day = 0;
  488.         while (i < daySegmentLength) {
  489.             day = day * 256 + toUnsigned(timeField[i++]);
  490.         }

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

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

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

  506.     }

  507.     /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  508.      * <p>
  509.      * CCSDS Calendar Segmented Time Code is defined in the blue book:
  510.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  511.      * </p>
  512.      * @param preambleField field specifying the format, often not transmitted in
  513.      * data interfaces, as it is constant for a given data interface
  514.      * @param timeField byte array containing the time code
  515.      * @return an instance corresponding to the specified date
  516.      * @throws OrekitException if preamble is inconsistent with Calendar Segmented Time Code,
  517.      * or if it is inconsistent with time field, or it UTC time scale cannot be retrieved
  518.      */
  519.     public FieldAbsoluteDate<T> parseCCSDSCalendarSegmentedTimeCode(final byte preambleField, final byte[] timeField)
  520.         throws OrekitException {

  521.         // time code identification
  522.         if ((preambleField & 0xF0) != 0x50) {
  523.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  524.                                       formatByte(preambleField));
  525.         }

  526.         // time field length
  527.         final int length = 7 + (preambleField & 0x07);
  528.         if (length == 14) {
  529.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  530.                                       formatByte(preambleField));
  531.         }
  532.         if (timeField.length != length) {
  533.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  534.                                       timeField.length, length);
  535.         }

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

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

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

  559.     }

  560.     /** Decode a signed byte as an unsigned int value.
  561.      * @param b byte to decode
  562.      * @return an unsigned int value
  563.      */
  564.     private static int toUnsigned(final byte b) {
  565.         final int i = (int) b;
  566.         return (i < 0) ? 256 + i : i;
  567.     }

  568.     /** Format a byte as an hex string for error messages.
  569.      * @param data byte to format
  570.      * @return a formatted string
  571.      */
  572.     private static String formatByte(final byte data) {
  573.         return "0x" + Integer.toHexString(data).toUpperCase();
  574.     }

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

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

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

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

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

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

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

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

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

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

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

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

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

  743.     /** Dummy date at infinity in the future direction.
  744.      * @param field field for the components
  745.      * @return FieldAbsoluteDate<T> FieldAbsoluteDate<T> representing {@link AbsoluteDate#FUTURE_INFINITY}
  746.      * @param <T> the type of the field elements
  747.      */
  748.     public static <T extends RealFieldElement<T>> FieldAbsoluteDate<T> getFutureInfinity(final Field<T> field) {
  749.         return new FieldAbsoluteDate<>(field, AbsoluteDate.FUTURE_INFINITY);
  750.     }

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

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

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

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

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

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

  862.     /** Split the instance into date/time components.
  863.      * @param timeScale time scale to use
  864.      * @return date/time components
  865.      */
  866.     public DateTimeComponents getComponents(final TimeScale timeScale) {

  867.         if (Double.isInfinite(offset.getReal())) {
  868.             // special handling for past and future infinity
  869.             if (offset.getReal() < 0) {
  870.                 return new DateTimeComponents(DateComponents.MIN_EPOCH, TimeComponents.H00);
  871.             } else {
  872.                 return new DateTimeComponents(DateComponents.MAX_EPOCH,
  873.                                               new TimeComponents(23, 59, 59.999));
  874.             }
  875.         }

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

  890.         // split date and time
  891.         final long   carry = (long) FastMath.floor(sum);
  892.         double offset2000B = (sum - carry) + residual;
  893.         long   offset2000A = epoch + carry + 43200l;
  894.         if (offset2000B < 0) {
  895.             offset2000A -= 1;
  896.             offset2000B += 1;
  897.         }
  898.         long time = offset2000A % 86400l;
  899.         if (time < 0l) {
  900.             time += 86400l;
  901.         }
  902.         final int date = (int) ((offset2000A - time) / 86400l);

  903.         // extract calendar elements
  904.         final DateComponents dateComponents = new DateComponents(DateComponents.J2000_EPOCH, date);
  905.         TimeComponents timeComponents = new TimeComponents((int) time, offset2000B);

  906.         if (timeScale.insideLeap(this)) {
  907.             // fix the seconds number to take the leap into account
  908.             timeComponents = new TimeComponents(timeComponents.getHour(), timeComponents.getMinute(),
  909.                                                 timeComponents.getSecond() + timeScale.getLeap(this).getReal());
  910.         }

  911.         // build the components
  912.         return new DateTimeComponents(dateComponents, timeComponents);

  913.     }

  914.     /** Split the instance into date/time components for a local time.
  915.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  916.      * negative Westward UTC)
  917.      * @return date/time components
  918.      * @exception OrekitException if UTC time scale cannot be retrieved
  919.      */
  920.     public DateTimeComponents getComponents(final int minutesFromUTC)
  921.         throws OrekitException {

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

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

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

  949.     }

  950.     /** {@inheritDoc} */
  951.     public FieldAbsoluteDate<T> getDate() {
  952.         return this;
  953.     }

  954.     /** Get the field.
  955.      * @return field instance.
  956.      */
  957.     public Field<T> getField() {
  958.         return field;
  959.     }

  960.     /** Split the instance into date/time components for a time zone.
  961.      * @param timeZone time zone
  962.      * @return date/time components
  963.      * @exception OrekitException if UTC time scale cannot be retrieved
  964.      */
  965.     public DateTimeComponents getComponents( final TimeZone timeZone)
  966.         throws OrekitException {
  967.         final long milliseconds = FastMath.round((offsetFrom(getJavaEpoch(field), TimeScalesFactory.getUTC()).getReal()) * 1000);
  968.         return getComponents(timeZone.getOffset(milliseconds) / 60000);
  969.     }

  970.     /** Compare the instance with another date.
  971.      * @param date other date to compare the instance to
  972.      * @return a negative integer, zero, or a positive integer as this date
  973.      * is before, simultaneous, or after the specified date.
  974.      */
  975.     public int compareTo(final FieldAbsoluteDate<T> date) {
  976.         return Double.compare(durationFrom(date).getReal(), 0.0);
  977.     }


  978.     /** Check if the instance represent the same time as another instance.
  979.      * @param date other date
  980.      * @return true if the instance and the other date refer to the same instant
  981.      */
  982.     @SuppressWarnings("unchecked")
  983.     public boolean equals(final Object date) {

  984.         if (date == this) {
  985.             // first fast check
  986.             return true;
  987.         }

  988.         if ((date != null) && (date instanceof FieldAbsoluteDate)) {
  989.             return durationFrom((FieldAbsoluteDate<T>) date).getReal() == 0.0;
  990.         }

  991.         return false;

  992.     }

  993.     /** Get a hashcode for this date.
  994.      * @return hashcode
  995.      */
  996.     public int hashCode() {
  997.         final long l = Double.doubleToLongBits(durationFrom(AbsoluteDate.J2000_EPOCH).getReal());
  998.         return (int) (l ^ (l >>> 32));
  999.     }

  1000.     /** Get a String representation of the instant location in UTC time scale.
  1001.      * @return a string representation of the instance,
  1002.      * in ISO-8601 format with milliseconds accuracy
  1003.      */
  1004.     public String toString() {
  1005.         try {
  1006.             return toString(TimeScalesFactory.getUTC());
  1007.         } catch (OrekitException oe) {
  1008.             throw new RuntimeException(oe);
  1009.         }
  1010.     }

  1011.     /** Get a String representation of the instant location.
  1012.      * @param timeScale time scale to use
  1013.      * @return a string representation of the instance,
  1014.      * in ISO-8601 format with milliseconds accuracy
  1015.      */
  1016.     public String toString(final TimeScale timeScale) {
  1017.         return getComponents(timeScale).toString(timeScale.minuteDuration(this));
  1018.     }

  1019.     /** Get a String representation of the instant location for a local time.
  1020.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  1021.      * negative Westward UTC).
  1022.      * @return string representation of the instance,
  1023.      * in ISO-8601 format with milliseconds accuracy
  1024.      * @exception OrekitException if UTC time scale cannot be retrieved
  1025.      */
  1026.     public String toString(final int minutesFromUTC)
  1027.         throws OrekitException {
  1028.         final int minuteDuration = TimeScalesFactory.getUTC().minuteDuration(this);
  1029.         return getComponents(minutesFromUTC).toString(minuteDuration);
  1030.     }

  1031.     /** Get a String representation of the instant location for a time zone.
  1032.      * @param timeZone time zone
  1033.      * @return string representation of the instance,
  1034.      * in ISO-8601 format with milliseconds accuracy
  1035.      * @exception OrekitException if UTC time scale cannot be retrieved
  1036.      */
  1037.     public String toString(final TimeZone timeZone)
  1038.         throws OrekitException {
  1039.         final int minuteDuration = TimeScalesFactory.getUTC().minuteDuration(this);
  1040.         return getComponents(timeZone).toString(minuteDuration);
  1041.     }

  1042.     /** Get a time-shifted date.
  1043.      * <p>
  1044.      * Calling this method is equivalent to call <code>new AbsoluteDate(this, dt)</code>.
  1045.      * </p>
  1046.      * @param dt time shift in seconds
  1047.      * @return a new date, shifted with respect to instance (which is immutable)
  1048.      * @see org.orekit.utils.PVCoordinates#shiftedBy(double)
  1049.      * @see org.orekit.attitudes.Attitude#shiftedBy(double)
  1050.      * @see org.orekit.orbits.Orbit#shiftedBy(double)
  1051.      * @see org.orekit.propagation.SpacecraftState#shiftedBy(double)
  1052.      */

  1053.     @Override
  1054.     public FieldAbsoluteDate<T> shiftedBy(final double dt) {
  1055.         return new FieldAbsoluteDate<>(this, dt);
  1056.     }


  1057.     /** Transform the FieldAbsoluteDate in an AbsoluteDate.
  1058.      * @return AbsoluteDate of the FieldObject
  1059.      * */
  1060.     public AbsoluteDate toAbsoluteDate() {
  1061.         return new AbsoluteDate(epoch, offset.getReal());
  1062.     }

  1063. }